python - 带有 Python 'Requests' 模块的代理

标签 python python-requests httprequest http-proxy

关于优秀的 Requests 的简短说明Python 模块。

我似乎无法在文档中找到变量“代理”应包含的内容。当我向它发送一个带有标准“IP:PORT”值的字典时,它拒绝了它要求 2 个值。 所以,我猜(因为这似乎没有在文档中涵盖)第一个值是 ip,第二个值是端口?

文档仅提及这一点:

proxies – (optional) Dictionary mapping protocol to the URL of the proxy.

所以我尝试了这个......我应该怎么做?

proxy = { ip: port}

我应该在将它们放入字典之前将它们转换为某种类型吗?

r = requests.get(url,headers=headers,proxies=proxy)

最佳答案

proxies 的 dict 语法是 {"protocol": "scheme://ip:port", ...}。有了它,您可以为使用 httphttpsftp 协议(protocol)的请求指定不同(或相同)的代理:

http_proxy  = "http://10.10.1.10:3128"
https_proxy = "https://10.10.1.11:1080"
ftp_proxy   = "ftp://10.10.1.10:3128"

proxies = { 
              "http"  : http_proxy, 
              "https" : https_proxy, 
              "ftp"   : ftp_proxy
            }

r = requests.get(url, headers=headers, proxies=proxies)

requests documentation 推导出来:

Parameters:
method – method for the new Request object.
url – URL for the new Request object.
...
proxies – (optional) Dictionary mapping protocol to the URL of the proxy.
...


在 linux 上,您还可以通过 HTTP_PROXYHTTPS_PROXYFTP_PROXY 环境变量执行此操作:

export HTTP_PROXY=10.10.1.10:3128
export HTTPS_PROXY=10.10.1.11:1080
export FTP_PROXY=10.10.1.10:3128

在 Windows 上:

set http_proxy=10.10.1.10:3128
set https_proxy=10.10.1.11:1080
set ftp_proxy=10.10.1.10:3128

关于python - 带有 Python 'Requests' 模块的代理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8287628/

相关文章:

python - 如何检查 Pandas 系列是否包含时间戳?

python - 从元组列表中获取前 5 个最大的 - Python

python - 无法解码 Python Web 请求

python - 无法使用 Python 的 requests 模块登录 ASP.NET 网站

html - 隐藏图像跟踪像素是否会导致问题(http 请求未通过)?

c# - 在 ASP.Net 中,我能否通过 session ID 确定另一个 session 是否存在或是否有效?

python - 如何清理字符串列表

python - SQLAlchemy:树节点中的递归混合属性

python - 使用 Python 和 beautifulsoup4 登录网站后如何抓取搜索结果?

python - Django:像 LoginView 这样的通用表单在哪里渲染函数字典填充以及如何更改它