网页=html框架+javascript行为+css样貌。浏览器会运行javascript和css对网元进行渲染,requests默认不会,因此浏览器看到的源代码比原始的html就有了变化,你在浏览器上能看到,但html里没有:import requests
url = "https://search.bilibili.com/all?keyword=%E7%BC%96%E7%A8%8B&spm_id_from=333.1007"
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:78.0) Gecko/20100101 Firefox/78.0'}
r = requests.get(url=url, headers=headers)
with open('r.txt', 'w') as f: # 把这个网页html保存会发现没有你要的数据,直接打开文件搜“2万多”
f.write(r.text)
然后实际的数据是在ajax里:
至于什么是ajax你百度吧,网上很多教程。import requests
ajax_url = 'https://api.bilibili.com/x/web-interface/search/all/v2?__refresh__=true&_extra=&context=&page=1&page_size=42' \
'&order=&duration=&from_source=&from_spmid=333.337&platform=pc&highlight=1&single_column=0&keyword=%E7%BC%96' \
'%E7%A8%8B&preload=true&com2co=true'
r = requests.get(url=ajax_url, headers=headers)
print(r.json()['data']['result'][10]['data'][0])
|