Python request.get 无法获得我可以在浏览器上打开的 url 的答案

标签 python python-requests

我正在学习如何使用 python requests (Python 3),并且我正在尝试制作一个简单的 requests.get 从多个网站获取 HTML 代码。虽然它对大多数人都有效,但有一个我遇到了麻烦。

当我打电话时:http://es.rs-online.com/一切正常:

In [1]: import requests
   ...:html = requests.get("http://es.rs-online.com/")
In [2]:html
Out[2]: <Response [200]>

但是,当我尝试使用 http://es.farnell.com/ 时,python 无法解析该地址并永远继续处理它。如果我设置超时,无论多长时间,requests.get() 都将始终被超时中断,而不会被其他任何情况中断。我也尝试过添加标题,但没有解决问题。另外,我认为该错误与我使用的代理没有任何关系,因为我可以在浏览器中打开该网站。目前,我的代码如下所示:

import requests
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.76 Safari/537.36'}
html = requests.get("http://es.farnell.com/",headers=headers, timeout=5, allow_redirects = True )

5 秒后,我收到预期的超时通知。

ReadTimeout: HTTPConnectionPool(host='es.farnell.com', port=80): Read timed out. (read timeout=5)

有人知道可能是什么问题吗?

最佳答案

问题出在你的标题上。请记住,当涉及到您发送的 header 内容时,某些网站比其他网站更宽松。为了解决该问题,您应该将当前 header 替换为:

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.76 Safari/537.36', "Upgrade-Insecure-Requests": "1","DNT": "1","Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8","Accept-Language": "en-US,en;q=0.5","Accept-Encoding": "gzip, deflate"}

我还建议您将 get 请求发送到 https://es.farnell.com/ 而不是 http://es.farnell.com/ ,删除 timeout = 5 并删除 allow_redirects = True (因为默认情况下为 True)

<小时/>

总而言之,您的代码应如下所示:

import requests


headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.76 Safari/537.36', "Upgrade-Insecure-Requests": "1","DNT": "1","Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8","Accept-Language": "en-US,en;q=0.5","Accept-Encoding": "gzip, deflate"}
html = requests.get("https://es.farnell.com",headers=headers)

希望这有帮助。

关于Python request.get 无法获得我可以在浏览器上打开的 url 的答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51154114/

相关文章:

python请求cookies日期格式

Python请求不清理连接导致端口溢出?

python - 在 tensorflow 中实现简单的线性代数运算

python - requests.exceptions.HTTPError 与 requests.HTTPError

python - Pyinstaller无法构建wxpython应用程序,缺少错误wx._xml

python - 查找并删除所有空关系列表对象

python - 如何将 cURL 翻译成 Python 请求语言?

Python 请求 - 客户端证书的 SSL 错误

python - 为 OCR 对齐文本

python - Openpyxl:使用 load_workbook 时为 'ValueError: Max value is 14'