简体   繁体   English

如何为 requests.get() 设置代理以在 Pycharm 中工作?

[英]How to setup proxies for requests.get() to work in Pycharm?

I'm trying to use requests function from PyCharm.我正在尝试使用 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)

It is giving me它给了我

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',))

But when I tried to run following from cmd, it worked.但是当我尝试从 cmd 运行以下命令时,它起作用了。

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

I tried following:我尝试了以下操作:

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

But none of my methods have been successful in setting the proxy in PyCharm.但是我的方法都没有成功在 PyCharm 中设置代理。 Any suggestions?有什么建议?

You are passing wrong dictionary keys to requests.get .您将错误的字典键传递给requests.get

According to docs, keys should be named http and https : https://requests.readthedocs.io/en/master/user/advanced/#proxies根据文档,密钥应命名为httphttpshttps://requests.readthedocs.io/en/master/user/advanced/#proxies

Example from docs:来自文档的示例:

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

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

But because proxies also could be configured through environment variables, your second approach is working: you're setting http_proxy and https_proxy environment variables.但是因为代理也可以通过环境变量配置,你的第二种方法是有效的:你设置http_proxyhttps_proxy环境变量。 And requests accept them as proxy configuration. requests接受它们作为代理配置。

Seems I have found a solution.似乎我找到了解决方案。

Pycharm -> Run -> Edit Configuration -> Environment Variable Pycharm -> 运行 -> 编辑配置 -> 环境变量

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM