只是一个简短的,简单的关于优秀的Python请求模块。

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

文档只提到了这一点:

代理-(可选)字典映射协议到代理的URL。

所以我尝试了这个…我该怎么办?

proxy = { ip: port}

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

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

当前回答

接受的答案对我来说是一个好的开始,但我一直得到以下错误:

AssertionError: Not supported proxy scheme None

修复这个问题是在代理url中指定http://:

http_proxy  = "http://194.62.145.248:8080"
https_proxy  = "https://194.62.145.248:8080"
ftp_proxy   = "10.10.1.10:3128"

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

我感兴趣的是,为什么原版对某些人有效,但对我无效。

编辑:我看到主要的答案现在更新了,以反映这一点:)

其他回答

经过测试,下面的代码可以工作。需要使用HTTPProxyAuth。

import requests
from requests.auth import HTTPProxyAuth


USE_PROXY = True
proxy_user = "aaa"
proxy_password = "bbb"
http_proxy = "http://your_proxy_server:8080"
https_proxy = "http://your_proxy_server:8080"
proxies = {
    "http": http_proxy,
    "https": https_proxy
}

def test(name):
    print(f'Hi, {name}')  # Press Ctrl+F8 to toggle the breakpoint.
    # Create the session and set the proxies.
    session = requests.Session()
    if USE_PROXY:
        session.trust_env = False
        session.proxies = proxies
        session.auth = HTTPProxyAuth(proxy_user, proxy_password)

    r = session.get('https://www.stackoverflow.com')
    print(r.status_code)

if __name__ == '__main__':
    test('aaa')

有点晚了,但是这里有一个包装器类,它简化了抓取代理,然后生成http POST或GET:

ProxyRequests

https://github.com/rootVIII/proxy_requests

接受的答案对我来说是一个好的开始,但我一直得到以下错误:

AssertionError: Not supported proxy scheme None

修复这个问题是在代理url中指定http://:

http_proxy  = "http://194.62.145.248:8080"
https_proxy  = "https://194.62.145.248:8080"
ftp_proxy   = "10.10.1.10:3128"

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

我感兴趣的是,为什么原版对某些人有效,但对我无效。

编辑:我看到主要的答案现在更新了,以反映这一点:)

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

import urllib

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

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

您可以在这里参考代理文档。

如果你需要使用代理,你可以用代理参数配置单个请求到任何请求方法:

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基本认证,请使用http://user:password@host.com/语法:

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