【问题标题】:How to properly use proxies in Python requests?如何在 Python 请求中正确使用代理?
【发布时间】:2020-05-10 20:11:35
【问题描述】:

我有一个代理列表。 当我使用curl 测试其中一个时:

curl -proxy https://x.x.x:port https://www.google.com/

我得到了预期的结果,但是当我运行时:

proxies = {'http' : 'x.x.x:port', 'https' : 'x.x.x:port'}
requests.get('https://www.google.com/', proxies = proxies)

卡了一会儿,然后我得到这个错误:

requests.exceptions.ProxyError: HTTPSConnectionPool(host='www.google.com', port=443): Max retries exceeded with url: / (Caused by ProxyError('Cannot connect to proxy.', ConnectionResetError(104, 'Connection reset by peer')))

我尝试了不同的代理定义方式,比如:

'http' : 'http://x.x.x:port', 'https' : 'https://x.x.x:port'

没有任何效果,总是出现这个错误,如何解决?

【问题讨论】:

    标签: python proxy python-requests


    【解决方案1】:

    编辑:刚刚看到您关于尝试不同方式的最后说明,这与我的第一个建议一致。您可能想在我稍后的建议中尝试使用 os 库设置代理。

    有两点让我印象深刻:

    1. 您在 curl 命令中使用了 https://x.x.x:port,但使用了 x.x.x:port 在 Python 中。您可能必须包含https://

    2. 您同时使用了 http 和 https。我认为这不会导致错误,但仍然值得研究

    首先,我建议像这样包含https://

    proxies = {'https' : 'https://x.x.x:port'}  
    requests.get('https://www.google.com/', proxies = proxies) 
    

    其次,我会尝试设置 https(如果失败,请尝试设置 http):

    import requests
    
    proxies = {
      'https': 'https://x.x.x.x:port',
    }
    
    requests.get('https://example.org', proxies=proxies)
    

    另外,您可以通过 Python 设置环境代理,例如:

    import os
    os.environ["http_proxy"] = "http://x.x.x.x:port"
    os.environ["https_proxy"] = "https://x.x.x.x:port"
    

    或通过命令行/命令提示符

    窗户

    set http_proxy=http://x.x.x.x:port
    set https_proxy=https://x.x.x.x:port
    

    Linux/OS X:

    export http_proxy=http://x.x.x.x:port
    export https_proxy=https://x.x.x.x:port
    

    【讨论】:

    • 感谢您的回答。我尝试设置环境代理,但仍然遇到相同的错误。看起来请求有问题,curl 完美。我也尝试只设置 https,包括 http 和 https,从 url 包含和排除模式,仍然没有。
    猜你喜欢
    • 2021-09-14
    • 2016-07-03
    • 2013-06-11
    • 2015-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-07
    • 2018-04-01
    相关资源
    最近更新 更多