【问题标题】:How to setup proxies for requests.get() to work in Pycharm?如何为 requests.get() 设置代理以在 Pycharm 中工作?
【发布时间】:2020-11-12 01:02:42
【问题描述】:

我正在尝试使用 PyCharm 的请求功能。

import requests
url = 'https://www.google.com'
ProxyDict = {"http_proxy":"http://proxy-us.MyCompany.com:911","https_proxy":"http://proxy-us.MyCompany.com:912"}
o = requests.get(url,proxies = ProxyDict)
print(o.status_code)

它给了我

requests.exceptions.ConnectionError: HTTPSConnectionPool(host='www.google.com', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x0000027CBF508B00>: Failed to establish a new connection: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond',))

但是当我尝试从 cmd 运行以下命令时,它起作用了。

$set http_proxy=http://proxy-us.MyCompany.com:911
$set https_proxy=http://proxy-us.MyCompany.com:912
$ python ip_locator.py
200

我尝试了以下操作:

  1. 设置名为 HTTP_PROXY 和 HTTPS_PROXY 的系统环境变量
  2. 在Pycharm中,Ctrl+Alt+S --> HTTP Proxy -> 自动代理配置 URL:http://proxy-us.MyCompany.com:911

但是我的方法都没有成功在 PyCharm 中设置代理。有什么建议吗?

【问题讨论】:

    标签: python proxy python-requests pycharm


    【解决方案1】:

    您将错误的字典键传递给requests.get

    根据文档,密钥应命名为httphttpshttps://requests.readthedocs.io/en/master/user/advanced/#proxies

    来自文档的示例:

    proxies = {
      'http': 'http://10.10.1.10:3128',
      'https': 'http://10.10.1.10:1080',
    }
    
    requests.get('http://example.org', proxies=proxies)
    

    但是因为代理也可以通过环境变量进行配置,所以您的第二种方法是有效的:您正在设置 http_proxyhttps_proxy 环境变量。并且requests 接受它们作为代理配置。

    【讨论】:

    • 正确。很棒的收获。谢谢
    【解决方案2】:

    看来我找到了解决办法。

    Pycharm -> 运行 -> 编辑配置 -> 环境变量

    PYTHONUNBUFFERED=1;http_proxy=http://proxy-us.MyCompany.com:911;https_proxy=http://proxy-us.MyCompany.com:912 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-29
      • 2013-09-27
      • 2016-05-18
      • 2013-12-22
      • 2016-08-19
      • 1970-01-01
      • 2023-01-24
      • 1970-01-01
      相关资源
      最近更新 更多