从网页提取出来的信息就是字典类型:content={'aid': 96393562, 'title': '【幼月的镜头工坊】女王:我想要的,就会是我的【7Rings】', 'tname': 'MMD·3D'} 但是在第三步保存数据到CSV的的时候就要报错,说'str' object has no attribute 'keys',怎么处理呢?
class BiliBili:
# 第一步:爬取目链接
def get_json(self, av_num):
fake = Factory().create()
headers = {'User-Agent': fake.user_agent()}
url = ('https://api.bilibili.com/x/web-interface/view?aid={}'.format(av_num))
response = requests.get(url, headers=headers)
self.parse_json(response)
# 第二步:解析页面提取关键信息
def parse_json(self, response):
html = json.loads(response.text)
content = {"aid": html["data"]["aid"], "title": html["data"]["title"], "tname": html["data"]["tname"]}
self.save_content(content)
# 第三步:保存数据
def save_content(self, content):
with open('B站视频信息.csv', 'w', newline="", encoding='utf-8') as f:
writer = csv.DictWriter(f, content.keys())
writer.writeheader()
writer.writerows(content)
# 第四步:遍历url
def main(self, start_av_num, end_av_num):
for av_num in range(start_av_num, end_av_num+1):
self.get_json(av_num)
# 执行函数
def main():
p = BiliBili()
p.main(96393562, 96393562)
if __name__ == '__main__':
main()