使用Python“请求”modu的代理

2024-04-19 04:49:45 发布

您现在位置:Python中文网/ 问答频道 /正文

只是一个简短的关于Python优秀的Requests模块的简单介绍。

我似乎在文档中找不到变量“proxies”应该包含什么。当我给它发送一个带有标准“IP:PORT”值的dict时,它拒绝了要求2个值的请求。 所以,我猜(因为文档中似乎没有涉及到这一点)第一个值是ip,第二个值是端口?

文件中只提到:

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

所以我试过这个。。。我该怎么办?

proxy = { ip: port}

我应该把它们转换成某种类型,然后再把它们放进字典里吗?

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

Tags: 模块文件the端口文档ip标准port
3条回答

你可以参考proxy documentation here

如果需要使用代理,可以使用proxies参数将各个请求配置为任何请求方法:

import requests

proxies = {
  "http": "http://10.10.1.10:3128",
  "https": "https://10.10.1.10:1080",
}

requests.get("http://example.org", proxies=proxies)

要在代理中使用HTTP Basic Auth,请使用http://user:password@host.com/语法:

proxies = {
    "http": "http://user:pass@10.10.1.10:3128/"
}

proxiesdict语法是{"protocol":"ip:port", ...}。使用它,您可以使用httphttp sftp协议为请求指定不同(或相同)的代理:

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

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

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

^{} documentation推断:

Parameters:
method – method for the new Request object.
url – URL for the new Request object.
...
proxies – (optional) Dictionary mappingprotocol 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

谢谢,杰伊指出这一点:
语法随请求2.0.0而改变 您需要向url添加架构:http://docs.python-requests.org/en/latest/user/advanced/#proxies

我发现urllib有一些非常好的代码来获取系统的代理设置,它们正好是可以直接使用的正确形式。你可以这样使用:

import urllib

...
r = requests.get('http://example.org', proxies=urllib.request.getproxies())

它工作得非常好,urllib也知道如何获得Mac OS X和Windows设置。

相关问题 更多 >