python - 通过 Python Requests 模块发出 HTTP 请求不能通过 curl 的代理工作?为什么?

标签 python proxy get http-request python-requests

使用这个 curl 命令我能够从 Bash 得到我正在寻找的响应

curl -v -u z:secret_key --proxy http://proxy.net:80  \
-H "Content-Type: application/json" https://service.com/data.json

I have already seen this other post on proxies with the Requests module

它帮助我用 Python 编写代码,但我需要通过代理发出请求。但是,即使提供了适当的代理,它也无法正常工作。也许我只是没有看到什么?

>>> requests.request('GET', 'https://service.com/data.json', \
>>> headers={'Content-Type':'application/json'}, \ 
>>> proxies = {'http' : "http://proxy.net:80",'https':'http://proxy.net:80'}, \
>>> auth=('z', 'secret_key'))

此外,在同一个 python 控制台上,我可以使用 urllib 发出请求使其成功。

>>> import urllib
>>> urllib.urlopen("http://www.httpbin.org").read()
---results---

即使尝试对非 https 地址的请求也无法正常工作。

>>> requests.get('http://www.httpbin.org')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Python/2.6/site-packages/requests/api.py", line 79, in get
   return request('get', url, **kwargs)
File "/Library/Python/2.6/site-packages/requests/api.py", line 66, in request
    prefetch=prefetch
File "/Library/Python/2.6/site-packages/requests/sessions.py", line 191, in request
    r.send(prefetch=prefetch)
File "/Library/Python/2.6/site-packages/requests/models.py", line 454, in send
    raise ConnectionError(e)
requests.exceptions.ConnectionError: Max retries exceeded for url:

Requests 是如此优雅和令人敬畏,但在这种情况下它怎么会失败呢?

最佳答案

问题实际上在于python的标准url访问库——urllib/urllib2/httplib。我不记得哪个库是确切的罪魁祸首,但为了简单起见,我们就称它为 urllib。不幸的是,urllib 没有实现通过 http(s) 代理访问 https 站点所需的 HTTP Connect 方法。我使用 urllib 添加功能的努力没有成功(自从我尝试以来已经有一段时间了)。所以不幸的是,我知道唯一可行的选择是在这种情况下使用 pycurl。

然而,有一个相对干净的解决方案,几乎与 python 请求的 API 完全相同,但它使用 pycurl 后端而不是 python 标准库。

库名为 human_curl .我自己使用过它并取得了很好的效果。

关于python - 通过 Python Requests 模块发出 HTTP 请求不能通过 curl 的代理工作?为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8482896/

相关文章:

docker - Kibana 5.5.1 位于 nginx 1.13 代理后面(dockerized)

PHP:获取数据自动声明为变量

python - 将轴/绘图区域保存/导出到文件,而不是图形

python - 循环 scikit-learn 机器学习数据集

python - 如何动态地将谓词传递给过滤函数?

python - 用 Python 解析 XML xml.sax : How does one "keep track" of where in the tree you are?

使用 TOR 获取代理的 Python selenium 适用于 firefox,但不适用于 chrome

java - 如何使用 HttpsUrlConnection 通过 SSL 连接使用代理身份验证?

python - 将文件返回给 WSGI GET 请求

python - Flask python断言错误: unimplemented method 'GET'