【Python学习笔记六】获取百度搜索结果以及百度返回“百度安全验证”问题解决

时间:2023-03-09 07:23:34
【Python学习笔记六】获取百度搜索结果以及百度返回“百度安全验证”问题解决

1.获取百度搜索结果页面主要是修改百度搜索url中的参数实现,例如查询的关键字为wd;

举例:https://www.baidu.com/s?wd=python",这样就可以查询到‘python’相关的内容

具体的参数届时可以参考:https://blog.csdn.net/ZustKe/article/details/83882345

2.通过python获取百度内容时,会出现返回的页面内容是“百度安全验证”的情况,像下面这样

【Python学习笔记六】获取百度搜索结果以及百度返回“百度安全验证”问题解决

这是因为设置header是没有设置accept参数,设置后就OK了。

惯例附代码:

import urllib.request

headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36 Edg/83.0.478.50',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9'
}
url = "https://www.baidu.com/s?wd=python" req = urllib.request.Request(url=url, headers=headers)
html = urllib.request.urlopen(req).read().decode('UTF-8', 'ignore')
print(html)