Python 从公司防火墙后面使用 urllib2 打开网站 - 11004 getaddrinfo 失败

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4847649/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 17:50:11  来源:igfitidea点击:

opening websites using urllib2 from behind corporate firewall - 11004 getaddrinfo failed

pythonurllib2firewall

提问by Ayyappa Das

I am trying to access a website from behind corporate firewall using below:-

我正在尝试使用以下方法从公司防火墙后面访问网站:-

password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_mgr.add_password(None, url, username, password)
auth_handler = urllib2.HTTPBasicAuthHandler(password_mgr)
opener = urllib2.build_opener(auth_handler) 
urllib2.install_opener(opener) 
conn = urllib2.urlopen('http://python.org')

Getting error

获取错误

URLError: <urlopen error [Errno 11004] getaddrinfo failed>

I have tried with different handlers (tried ProxyHandler also in slightly different way), but doesn't seem to work.

我尝试过使用不同的处理程序(也以稍微不同的方式尝试过 ProxyHandler),但似乎不起作用。

Any clues to what could be the reason for error and any different ways to supply the credentials and make it work?

任何可能是错误原因的线索以及提供凭据并使其工作的任何不同方法?

回答by Senthil Kumaran

If you are using Proxy and that proxy has Username and Password (which many corporate proxies have), you need to set the proxy handler with urllib2.

如果您使用代理并且该代理具有用户名和密码(许多公司代理都有),则需要使用 urllib2 设置代理处理程序。

  proxy_url = 'http://' + proxy_user + ':' + proxy_password + '@' + proxy_ip
  proxy_support = urllib2.ProxyHandler({"http":proxy_url})
  opener = urllib2.build_opener(proxy_support,urllib2.HTTPHandler)
  urllib2.install_opener(opener)

HTTPBasicAuthHandler is used to provide credentials for the site which you are going to access and not for going through the proxy. The above snippet might help you.

HTTPBasicAuthHandler 用于为您将要访问的站点而不是通过代理提供凭据。上面的代码片段可能对您有所帮助。

回答by Alec Chu

On Windows, I observed that python uses the IE Internet Options-> LAN Settingssettings. So even if we use urllib2to install opener and specify the proxy_url, it would continue to use the IE settings.

在 Windows 上,我观察到 python 使用这些IE Internet Options-> LAN Settings设置。所以即使我们urllib2用来安装 opener 并指定了proxy_url,它也会继续使用 IE 设置。

It worked fine finally, when I exported a system variable:

当我导出系统变量时,它最终运行良好:

http_proxy=http://userid:[email protected]:port