首页 > IT职业 > IT职场 > 教你用python获取百度热榜链接

目标网址:
(推荐教程:Python入门教程)
https:///
要获取的内容:

链接分析:
从下图可以看出只需要获取关键字,再构建就可以了。

完整代码:
import requests
import pprint
import re
import urllib.parse
url = 'https:///'
headers = {
'Host': '',
'Referer': 'https:///',
'User-Agent': 你的User-Agent,
'Cookie': 你的Cookie
}
response = requests.get(url, headers=headers).content.decode('utf-8')
# 获取关键字
pat = '"pure_title": "(.*?)"'
keyword = re.findall(pat, response, re.S)
print(len(keyword))
for hot_word in keyword:
# 汉字不符合url标准,所以这里需要进行url编码
i = urllib.parse.quote(hot_word, encoding='utf-8', errors='replace')
# url构建
link = f'https:///s?cl=3&tn=baidutop10&fr=top1000&wd={i}&rsv_idx=2&rsv_dl=fyb_n_homepage&hisfilter=1'
print(link)
你会发现结果很长:

但其实关键字后面的几个参数是可以去掉的,这样url就没有那么长了。

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/912/viewspace-2832690/ ,如需转载,请注明出处,否则将追究法律责任。