2015-12-02 68 views
0

我的代碼只需要通過代理連接到一個網頁頁面,但百達收到以下錯誤,當reachs的「urllib2.urlopen」句:的Python的urllib2代理ASCII錯誤

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) 

Anaconda的運行的Python 2.7, Windows 7 64位。

我的代碼:

# -*- coding: utf-8 -*- 
import socks 
import urllib2 

def urllib2_HTTP_test(): 
    socks.set_default_proxy(socks.HTTP, "<proxy_address>", <proxy_port>) 
    socks.wrap_module(urllib2) 
    status = urllib2.urlopen("http://www.python.org:80").getcode() 
    assert status == 200 

if __name__ == "__main__": 
    urllib2_HTTP_test() 
+0

請出示充分堆棧跟蹤,它可能包含內部元素。 –

+0

謝謝Serge,我的第一篇文章缺乏經驗 –

+0

你襪子庫的實現有誤。請參閱[https://github.com/Anorov/PySocks#sockssocksocket](https://github.com/Anorov/PySocks#sockssocksocket) – Valijon

回答

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)