前言
此篇文章之前已经写过关于虎牙直播的抓取分析了,详情请访问https://blog.csdn.net/MarkAdc/article/details/90048758
代码
import requests
import json
import xlwt
class Spider:
def __init__(self):
# 生成表格对象
self.wb = xlwt.Workbook()
# 在表格中新增一张表
self.ws = self.wb.add_sheet("sheet1", cell_overwrite_ok=True)
# 记录行数,表格写入数据时将依据self.count来判断将数据写在哪一行
self.count = 0
# 在这里不指定具体抓取哪一页,使用字符串的format方法以便后面灵活调整页数
self.url = 'https://www.huya.com/cache.php?m=LiveList&do=getLiveListByPage&tagAll=0&page={}'
# 生成器,保存的是每一页的数据,有多个item
def parse(self, url):
response = requests.get(url)
response.encoding = 'utf-8'
assert response.status_code == 200 # 断言一下状态码是200
json_dict = json.loads(response.text) # 把响应的json数据转换成python的字典
infos = json_dict['data']['datas'] # 每一页的直播间数据全在这里面,一共120个
for info in infos:
item = {}
item['标题'] = info['introduction']
item['类型'] = info['gameFullName']
item['主播'] = info['nick']
item['网址'] = 'https://www.huya.com/' + info['profileRoom']
item['人气'] = info['totalCount']
print(item)
# 生成数据并依次返回,一个主播对应一个item
yield item
# 写入表格中
def write_excel(self, item):
key_list = []
value_list = []
for data in item:
key_list.append(data)
value_list.append(item[data])
if self.count == 0:
for i in range(0, len(key_list)):
self.ws.write(0, i, key_list[i])
for i in range(0, len(value_list)):
self.ws.write(1 + self.count, i, value_list[i])
self.count += 1
# 程序入口
def run(self):
for page in range(1, 31): # 构造将要抓取的具体页数,此处是1-30页
for item in self.parse(spider.url.format(page)):
self.write_excel(item) # 向表格中写入数据
self.wb.save("虎牙直播间信息.xlsx") # 数据写完完保存到本地
if __name__ == '__main__':
spider = Spider()
spider.run()
说明
不耐烦的小伙伴可以直接复制代码,直接在你的电脑上运行即可。