本文介绍了python urllib2可以打开localhost但不能打开127.0.0.1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用python urllib2库,可以看到一个奇怪而令人讨厌的问题.

I am using python urllib2 library and can see a strange and nasty problem.

Windows 7.

我的代码:

import urllib2 as url_request


opener = url_request.build_opener(url_request.ProxyHandler({'http': 'http://login:password@server:8080'}))
request = url_request.Request("http://localhost");
response = opener.open(request)
print response.read()

它工作得很好,但是当我将localhost更改为127.0.0.1时,会发生此错误:

It works perfectly well, but when I change localhost to 127.0.0.1 this error happens:

HTTPError: HTTP Error 502: Proxy Error ( Forefront TMG denied the specified Uniform Resource Locator (URL).  )

可以成功打开google.com等其他地址.唯一的问题是127.0.0.1

Another addresses like google.com can be opened sucessfully.The only problem is 127.0.0.1

有什么想法吗?

推荐答案

使用127.0.0.1(也可以选择使用localhost)设置no_proxyNO_PROXY环境密钥:

Set a no_proxy or NO_PROXY environment key with 127.0.0.1, optionally with localhost too:

import os

os.environ['no_proxy'] = '127.0.0.1,localhost'

在Windows上,还请参考HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings注册表中的ProxyOverride项,您可能已将localhost注册为异常.检查您的代理设置以验证这一点.

On Windows the ProxyOverride key in the HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings registry is consulted as well, you probably have localhost registered as exception. Check your proxy settings to verify this.

这篇关于python urllib2可以打开localhost但不能打开127.0.0.1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 19:49