gpt4 book ai didi

python urllib.request - 可能有效的 header

转载 作者:行者123 更新时间:2023-12-04 12:51:21 26 4
gpt4 key购买 nike

正在编写一个从网站获取信息的小脚本。我遇到了 HTTP 错误问题。

req = urllib.request.Request(lnk['href'],
headers={'User-Agent': 'Mozilla/5.0', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'})
page = urllib.request.urlopen(req)

例如,当尝试获取 http://www.guru99.com/node-js-tutorial.html 时,我收到一长串错误,以 406 Unacceptable 结尾:

Traceback (most recent call last):
File "get_links.py", line 45, in <module>
page = urllib.request.urlopen(req)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 162, in urlopen
return opener.open(url, data, timeout)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 471, in open
response = meth(req, response)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 581, in http_response
'http', request, response, code, msg, hdrs)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 509, in error
return self._call_chain(*args)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 443, in _call_chain
result = func(*args)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 589, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 406: Not Acceptable

谷歌搜索我发现我应该修复标题(就像我上面所做的那样)和很多关于如何修复标题的教程。除了 - 实际上没有多少作用。

是否有一些可能不会对大多数站点造成问题的良好标题集?是否有其他人创建的一些 python 模块已经包含常用的头文件?有没有一种好方法可以使用不同的 header 重试几次,直到获得良好的响应?

这似乎是每个使用 Python 进行网页抓取的人都会遇到的问题,但我还没有找到合适的解决方案。

最佳答案

HTTP 错误 406 Not Acceptable

The HyperText Transfer Protocol (HTTP) 406 Not Acceptable client errorresponse code indicates that the server cannot produce a responsematching the list of acceptable values defined in the request'sproactive content negotiation headers, and that the server isunwilling to supply a default representation.

所以我可以看出问题出在您的 User-Agent: Mozilla/5.0 键和值上。这是一堆正确的用户代理的链接,

因此将您的代码更改为以下内容,

headers={'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'})

我知道答案为时已晚,但希望这对其他人有帮助。

关于python urllib.request - 可能有效的 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37803365/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com