我的代码只需要通过代理连接到网页页面,但是当到达" urllib2.urlopen"时,总是会收到以下错误:句:
log( string nameValue) {
attrs::mutable_constant< string > Name(nameValue);
logger::get().add_attribute("Name", Name);
Name.set(nameValue);
cout << "name is: " << Name;
}
在Anaconda中运行Python 2.7,Windows 7 64位。
我的代码:
Traceback (most recent call last):
File "C:\Anaconda\lib\site-packages\IPython\core\interactiveshell.py", line 3052, in run_code
self.showtraceback()
File "C:\Anaconda\lib\site-packages\IPython\core\interactiveshell.py", line 1851, in showtraceback
value, tb, tb_offset=tb_offset)
File "C:\Anaconda\lib\site-packages\IPython\core\ultratb.py", line 1240, in structured_traceback
self, etype, value, tb, tb_offset, number_of_lines_of_context)
File "C:\Anaconda\lib\site-packages\IPython\core\ultratb.py", line 1157, in structured_traceback
self, etype, value, elist, tb_offset, number_of_lines_of_context
File "C:\Anaconda\lib\site-packages\IPython\core\ultratb.py", line 511, in structured_traceback
lines = ''.join(self._format_exception_only(etype, value))
File "C:\Anaconda\lib\site-packages\IPython\core\ultratb.py", line 623, in _format_exception_only
Colors.Normal, s))
UnicodeDecodeError: 'ascii' codec can't decode byte 0xf3 in position 110: ordinal not in range(128)
答案 0 :(得分:0)
您可以使用urllib2.ProxyHandler
,试试这个:
def urllib2_HTTP_test():
proxy = urllib2.ProxyHandler({'http': '<proxy>:<port>'})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
status = urllib2.urlopen("http://www.python.org:80").getcode()
assert status == 200
或使用pycurl
,因为我更喜欢这样的东西:
import pycurl
def pycurl_HTTP_test(url, proxy, proxy_usr):
c = pycurl.Curl()
c.setopt(c.URL, url)
c.setopt(pycurl.PROXY, proxy) #<-- ex. 'http://proxy:port'
c.setopt(pycurl.PROXYUSERPWD, proxy_usr) #<-- ex. 'usr:pass'
c.setopt(c.FAILONERROR, True)
c.setopt(pycurl.VERBOSE, False)
c.setopt(pycurl.FOLLOWLOCATION, 1)
try:
c.perform()
except pycurl.error, error:
errno, errstr = error
print 'An error occurred: ', errstr
status = c.getinfo(pycurl.HTTP_CODE)
assert status == 200
if __name__ == "__main__":
url = "http://www.python.org:80"
proxy = 'http://proxy:port'
proxy_usr = 'usr:pass'
pycurl_HTTP_test(url, proxy, proxy_usr)