豆瓣爬虫——通过json接口获取数据
2024-08-30 09:58:48
最近在复习resqusts 爬虫模块,就重新写了一个豆瓣爬虫,这个网页从HTML
源码上来看是没有任何我想要的信息的,如下图所示:
这是网页视图,我在源码中查找影片信息,没有任何信息,如图:
由此我判断数据是通过js封装过的,于是开始抓包,包也不多,排除一下就能找到json的接口,从接口进去是这样的:
而这些就正是我想要的数据,这些数据包括评分,名字,链接等等,但是不是标准的json,而是被封装到了一个名为
subjects 的key中,所以提取数据的时候还需要多一步操作,把数据从subjects
中提取出来
开始构建带代码:
先构建run()函数,搭建思路:
def run(self):
# 1.请求接口获取数据 response = self.get_page(self.start_url) # 2.将数据格式化 result = self.data_wash(response) # 3.写入mongodb self.save_db(result) # 4. 写入本地json保存
如此,基本的思路就清晰了,我只用按照这个思路一步步实现,就完成了。完整代码如下:
import requests
import json
import pymongo
class douBan:
def init(self):
self.client = pymongo.MongoClient()
self.db = self.client.DouBanself.headers = {'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Mobile Safari/537.36'}
self.start_url = 'https://movie.douban.com/j/search_subjects?type=movie&tag=%E7%83%AD%E9%97%A8&page_limit=5050&page_start=0'
def get_page(self,url):
''' :param url: 请求地址
:return: 返回response
'''
url = url
response = requests.get(url,headers=self.headers).content.decode()
return response
def data_wash(self,response):
ret = json.loads(response)
ret =ret['subjects']
print(type(ret))
return ret def run(self):
# 1.请求接口获取数据
response = self.get_page(self.start_url)
# 2.将数据格式化
result = self.data_wash(response)
# 3.写入mongodb
self.save_db(result)
# 4. 写入本地json保存 def save_db(self,data):
collection = self.db.Movie4
with open('douban.json','w',encoding='utf-8') as f:
f.write(json.dumps(data,ensure_ascii=False,indent=2))
print('本地写入成功') ret = collection.insert_many(data)
print(ret,"写入数据库成功") if __name__ == '__main__':
douban = douBan()
douban.run()
代码很简单,但功能是实现了。后期如果想爬取其他分类,只用在start
中修改就可以实现。代码会逐步完善。
结果如下:本地json 文件:
./media/image4.png
数据库端如下:
最新文章
- 虚拟机+apache+php+mysql 环境安装配置
- Hibernate一些防止SQL注入的方式
- Educational Codeforces Round 16 C
- [大牛翻译系列]Hadoop(9)MapReduce 性能调优:理解性能瓶颈,诊断map性能瓶颈
- bzoj1877: [SDOI2009]晨跑
- Quartz 有状态的JobDataMap
- 我的第一个Android项目之环境搭建
- 【物联网云端对接-1】 通过HTTP协议与微软Azure IoT hub进行云端通信
- Apache Mina入门实例
- AVL树的旋转操作详解
- 2016计蒜之道复赛B题:联想专卖店促销
- mysql中group by和order by同时使用无效的替代方案
- BigDecimal的加减乘除及比较大小
- 用C#语言编写:集合管理器
- pyc反编译-uncompyle2的安装及使用
- 用JS实现实时显示系统时间
- css自适应布局之“圣杯双飞翼”
- LeetCode题解之 Subtree of Another Tree
- spring注解@Scheduled中fixedDelay、fixedRate和cron表达式的区别
- json keyname map
热门文章
- Nginxre quest_time 和upstream_response_time
- org.apache.jasper.runtime.ELContextImpl cannot be cast to org.apache.jasper.el.ELContextImpl
- vue 判断页面是否滚动到底部
- 使用 juqery.media.js 实现 pdf 预览
- JAVA中Map集合遍历
- 【经验】基于阿里云 Ubuntu 的 LAMP 网站搭建及配置完全教程
- wordpress中遇到的问题
- 论文翻译:2019_Deep Neural Network Based Regression Approach for A coustic Echo Cancellation
- java泛型中<;?>;和<;T>;
- C++ switch 语句的用法