【问题标题】:How can I set a single proxy for a requests session object?如何为请求会话对象设置单个代理?
【发布时间】:2015-06-15 05:22:33
【问题描述】:

我正在使用 Python requests 包发送 http 请求。我想向请求会话对象添加一个代理。例如。

session = requests.Session()
session.proxies = {...} # Here I want to add a single proxy

目前我正在遍历一堆代理,并且在每次迭代时都会创建一个新会话。我只想为每次迭代设置一个代理。

我在文档中看到的唯一示例是:

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

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

我试图遵循这个,但无济于事。这是我的脚本代码:

# eg. line = 59.43.102.33:80
r = s.get('http://icanhazip.com', proxies={'http': 'http://' + line})

但我得到一个错误:

requests.packages.urllib3.exceptions.LocationParseError: Failed to parse 59.43.102.33:80

如何在会话对象上设置单个代理?

【问题讨论】:

    标签: python python-requests


    【解决方案1】:

    除了@neowu'的回答,如果你想为会话对象的生命周期设置代理,你还可以执行以下操作 -

    import requests
    proxies = {'http': 'http://10.11.4.254:3128'}
    s = requests.session()
    s.proxies.update(proxies)
    s.get("http://www.example.com")   # Here the proxies will also be automatically used because we have attached those to the session object, so no need to pass separately in each call
    

    【讨论】:

    • 这是一个更好的方法。
    • 感谢@BugHunterUK
    • 奇怪的是,当我像这样为会话设置代理时,它对我来说失败了(使用ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 403 Forbidden',))),但是如果我将完全相同的字典传递给get 方法,它工作正常.
    • 啊,刚刚发现问题 - 如果您在环境中定义了其他代理,请使用 session.trust_env=False 确保为会话定义的代理不会被环境覆盖(在我的情况下,我们为不同的任务使用不同的代理)。
    • 如果您这样做,您可能会使用自签名证书,该证书将抛出 [SSL: CERTIFICATE_VERIFY_FAILED] 以超越使用 s.verify =错误
    【解决方案2】:

    其实你是对的,但是你必须确保你对'line'的定义,这个我试过了,没关系:

    >>> import requests
    >>> s = requests.Session()
    >>> s.get("http://www.baidu.com", proxies={'http': 'http://10.11.4.254:3128'})
    <Response [200]>
    

    你有没有定义像line = ' 59.43.102.33:80'这样的行,地址前面有一个空格。

    【讨论】:

    • 每行开头都有一个空格。最简单的事情总是最能欺骗我,哈哈。谢谢:)
    • 注意:如果您使用的是代理服务器,例如squid,这不会让您使用相同的 IP 地址。即后续的s.get 将使用原始代理/实际ip。
    【解决方案3】:

    除了您目前获得的解决方案之外,还有其他方法可以设置代理:

    import requests
    
    with requests.Session() as s:
        # either like this
        s.proxies = {'https': 'http://105.234.154.195:8888', 'http': 'http://199.188.92.69:8000'}
        # or like this
        s.proxies['https'] = 'http://105.234.154.195:8888'
        r = s.get(link)
    

    【讨论】:

    • 这与上述答案中的s.proxies.update(proxies) 有何不同?
    【解决方案4】:

    希望这可能会导致答案:

    urllib3.util.url.parse_url(url) 给定一个 url,返回一个解析后的 Url namedtuple。尽力解析不完整的 url。未提供的字段将为无。

    取自https://urllib3.readthedocs.org/en/latest/helpers.html

    【讨论】:

      猜你喜欢
      • 2015-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-14
      • 2021-09-04
      相关资源
      最近更新 更多