python urllib.request - 可能有效的 header

标签 python web-scraping http-headers urllib

正在编写一个从网站获取信息的小脚本。我遇到了 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 error response code indicates that the server cannot produce a response matching the list of acceptable values defined in the request's proactive content negotiation headers, and that the server is unwilling 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/

相关文章:

python - 无法将 pip 升级到最新版本 9.0.1 (OS :ubuntu 16. 04LTS)

c# - HttpClient - 返回的内容与浏览器不同

python - 按数值 Python 对对象的实例进行排序

c++ - 使用c++使用http POST发送文件

python - 如何生成整数的随机正态分布

python - hvplot - 如何按分类变量对点数据着色并与 `ds.count_cat(.)` 聚合

python - logging.handlers.SMTPHandler 引发 smtplib.SMTPAuthenticationError

html - 通过 VBA 使用 QuerySelector 单击 HTML 元素

javascript - 离开网站后,AJAX 页面加载/history.pushState 无法正常工作

python - 检测格式错误的 Accept-Language HTTP header