python爬⾍——通过API爬取动态⽹站的数据
加粗样式在我前⾯的博客中,通过利⽤python的requests库和BeautifulSoup库对静态⽹站进⾏爬取,但如果遇到动态⽹站怎么办呢?接下来我们试着通过API来对动态⽹站进⾏爬取想要的数据。
⽬录
(⼀) 动态⽹站和静态⽹站的区别与
(⼆) 爬取QQ⾳乐——“⾬爱”的⼀页评论
import requests
sql语句where多条件查询
queueuserworkitem传参方式# 设置headers参数
headers ={
'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'
}
# 设置params参数
params ={
'g_tk':'5381',
'loginUin':'0',
'hostUin':'0',
'format':'json',
'inCharset':'utf8',
'outCharset':'GB2312',
'notice':'0',
'platform':'yqq.json',
'needNewCode':'0',启动多个dubbo
'cid':'205360772',chart控件柱状图
'reqtype':'2',
'biztype':'1',
'topid':'645819',
'cmd':'8',
'needmusiccrit':'0',
'pagenum':'0',
'pagesize':'25',
'lasthotcommentid':'',
'domain':'qq',
'ct':'24',
'cv':'10101010',
}
# 请求与⽹站的连接
training中文怎么读res = ('c.y.qq/base/fcgi-bin/fcg_global_comment_h5.fcg', headers = headers, params = params)
# 解析JSON
data = res.json()
# 将⼀页的评论全部打印出来
for item in data['comment']['commentlist']:
print('{}: {}'.format(item['nick'], item['rootcommentcontent']))
运⾏结果如下:
⼤家可能发现跟爬取静态⽹站代码相⽐有两个地⽅代码不同,第⼀个是params参数,它的作⽤是以字典的形式传递链接的查询字符串参数,使代码看上去更加的整洁明了,让我们上⾯获取的Request URL变得更简洁,有兴趣的朋友可以⾃⼰去了解下,直接⽤原来的Request URL也是可以的;第⼆个地⽅是多了⼀个解析JSON,这个的作⽤是将刚才获取的数据(也就是JSON),转换成字典。
(三) 爬取QQ⾳乐——“⾬爱”的多页评论
在学会怎么爬取⼀页评论后,我们来怎么爬取多页或者所有的评论。⾸先在第⼀页评论中打开开发者⼯具(ctrl+shift+i),然后点击Network,再选择XHR,再点击刚才那个请求,再点击它Headers,再点开Query String Parameters。再打开第⼆页评论重复上述步骤,对⽐它们的Query String Parameters,我们可以发现其中的pagenum和lasthotcommentid两个的值发⽣了变化。
可以多打开⼏页的评论,我们发现pagenum每次都加1,相当于翻了⼀页;⽽ lasthotcommentid 是上⼀页最后⼀个评论的commentid,相当于连接两页评论的标识。到规律后我们就可以开始写我们的整个代码啦!我们先爬取前五页的评论试试。
import time
# 设置headers参数
headers ={
'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36' }
# 爬取前五页的评论
for pagenum in range(5):
# 第⼀次lasthotcommentid为空
lasthotcommentid =''
params ={
'g_tk':'5381',
'loginUin':'0',
'hostUin':'0',
'format':'json',
'inCharset':'utf8',
'outCharset':'GB2312',
'notice':'0',
'platform':'yqq.json',
'needNewCode':'0',
'cid':'205360772',
'reqtype':'2',
'biztype':'1',
'topid':'645819',
'cmd':'8',
'needmusiccrit':'0',
'pagenum': pagenum,
# pagesize改为100,可以提⾼爬取速度
'pagesize':'25',
'lasthotcommentid': lasthotcommentid,
'domain':'qq',
'ct':'24',
'cv':'10101010',
}
# 请求与⽹站的连接
res = ('c.y.qq/base/fcgi-bin/fcg_global_comment_h5.fcg', headers=headers, params=params)
# 解析JSON
data = res.json()
# 将⼀页的评论全部打印出来
for item in data['comment']['commentlist']:
print('{}: {}'.format(item['nick'], item['rootcommentcontent']))
python请求并解析json数据# 当前页最后⼀个评论的 commentid 作为下⼀页的 lasthotcommentid
lasthotcommentid = data['comment']['commentlist'][-1]['commentid']
# 防⽌爬取太快被封
time.sleep(1)
⼤哈。如果⼤家有什么问题请随时指正,互相学习,⼀起进步!