本期用到
json,requests
库来爬取网页信息,这次爬的是一个特殊多页式网站,普通多页式网站只需分析不同页面的url,找出其中的不同点,用for in
来循环即可,但是斗鱼的https://www.douyu.com/directory/game/LOL中不同页面都是相同的url,这就需要去“F12”来寻找其中的区别。
工具.环境:Python3.6.5,Pycharm,windows10,Firefox

1.首先来寻找不同页面的区别
以斗鱼的LOL板块为例:https://www.douyu.com/directory/game/LOL
尝试切换不同页面都是相同的url,那怎么办呢??????????
按F12呼出开发者工具(在这推荐使用Firefox或chrome浏览器,我用的是Firefox)

要详细学习开发者工具的请自行百度,这里直接选择
网络
,会看到很多数据,数据发送方法分两种,为“post”and“get”。再选择XHR
,点击左上角的删除键,再重新载入网页,就会看到电脑又向服务器发送了多个请求。
再重复多换几个页面,发现每次换的页码都与其中一个请求名相同

点击该条信息,在右边显示该条信息的
消息头
,有一个请求网址https://www.douyu.com/gapi/rkc/directory/2_1/3,把它复制下来,发现末尾的3就是对应的页数。 OK 第一步结束!
2.get页面信息
打开1中get到的网址https://www.douyu.com/gapi/rkc/directory/2_1/3

发现里面有我想要爬取的斗鱼房间信息,那么就是它了,接下来要对它进行解剖。
(1)运用requests
来get该网页的信息
import requests
import json
urls = ['https://www.douyu.com/gapi/rkc/directory/2_1/{}'.format(page) for page in range(1, 5)]
for url in urls:
res = requests.get(url)
print(res.text) # 可以想先看看get到的是个什么东西
这里运用for in
循环来get到1-5页的网页信息for page in range(1, 5)
,具体见上面代码
(2)运用json
库来将已编码的 JSON 字符串解码为 Python 对象
import requests
import json
urls = ['https://www.douyu.com/gapi/rkc/directory/2_1/{}'.format(page) for page in range(1, 5)]
for url in urls:
res = requests.get(url)
j = json.loads(res.text)
print(j) # 可以看到已解码的对象
json.dumps
:将 Python 对象编码成 JSON 字符串
json.loads
:将已编码的 JSON 字符串解码为 Python 对象
3.处理对象数据

看到了一堆糊糊,这时Firefox的优势就体现出来了

可以看到各层的所属关系,便于接下来的提取数据,下面是完整代码:
import requests
import json
urls = ['https://www.douyu.com/gapi/rkc/directory/2_1/{}'.format(page) for page in range(1, 5)]
for url in urls:
res = requests.get(url)
j = json.loads(res.text)
l1 = j['data'] # 通过观察可以发现要的数据在data下
l2 = l1['rl'] #在观察发现在data的rl中
tplt = '{0:{4}<20}\t{1:<12}\t{2:{4}<25}\t{3:<12}'
print(tplt.format('主播', '房间号', '房间名', '热度', chr(12288)))
for i in range(len(l2)): # 这里用到for循环来处理一个列表下多个字典的数据
zhubo = l2[i]['nn']
room = l2[i]['rid']
redu = l2[i]['ol']
roomname = l2[i]['rn']
print(tplt.format(zhubo, room, roomname, redu, chr(12288)))
4.结果
运行程序

遇到的问题:在名字中出现中英文混合的字符,会出现对不了齐的问题,有解决方法的可以在评论区分享!谢谢
预告:下一个会教你获取一个房间弹幕词云分析,记得关注哦!
发现错误的可以大力提出,一起交流学习
网友评论