2013-05-27 151 views
3

我試圖谷歌和stackOverflow上搜索類似的問題,但仍然無法解決我的問題。Python和代理 - urllib2.URLError:<urlopen錯誤[Errno 110]連接超時>

我需要我的python腳本通過代理執行http連接。
下面是我的測試腳本:

import urllib2, urllib 

proxy = urllib2.ProxyHandler({'http': 'http://255.255.255.255:3128'}) 
opener = urllib2.build_opener(proxy, urllib2.HTTPHandler) 
urllib2.install_opener(opener) 

conn = urllib2.urlopen('http://www.whatismyip.com/') 
return_str = conn.read() 

webpage = open('webpage.html', 'w') 
webpage.write(return_str) 
webpage.close() 

這個腳本作品在我的本地計算機(Windows 7,Python的2.7.3)上的精絕,但是當我嘗試在服務器上運行它,它給了我下面的錯誤:

Traceback (most recent call last): 
    File "proxy_auth.py", line 18, in <module> 
    conn = urllib2.urlopen('http://www.whatismyip.com/') 
    File "/home/myusername/python/lib/python2.7/urllib2.py", line 126, in urlopen 
    return _opener.open(url, data, timeout) 
    File "/home/myusername/python/lib/python2.7/urllib2.py", line 400, in open 
    response = self._open(req, data) 
    File "/home/myusername/python/lib/python2.7/urllib2.py", line 418, in _open 
    '_open', req) 
    File "/home/myusername/python/lib/python2.7/urllib2.py", line 378, in _call_chai            n 
    result = func(*args) 
    File "/home/myusername/python/lib/python2.7/urllib2.py", line 1207, in http_open 
    return self.do_open(httplib.HTTPConnection, req) 
    File "/home/myusername/python/lib/python2.7/urllib2.py", line 1177, in do_open 
    raise URLError(err) 
urllib2.URLError: <urlopen error [Errno 110] Connection timed out> 

我也試過使用requests庫,並得到了同樣的錯誤。

# testing request library 
r = requests.get('http://www.whatismyip.com/', proxies={'http':'http://255.255.255.255:3128'}) 

如果我沒有設置代理,那麼程序工作正常。

# this works fine 
conn = urllib2.urlopen('http://www.whatismyip.com/') 

我認爲問題是,在我的共享主機帳戶不可能設置代理環境變量...或類似的東西。

是否有任何解決方法或替代方法可以讓我爲http連接設置代理?我應該如何修改我的測試腳本?

+0

'ping www.whatismyip.com'在服務器上? – iMom0

+0

'ping:icmp open socket:不允許操作' – Olexiy

+0

服務器是什麼操作系統?這聽起來像服務器沒有配置爲允許以您期望的方式發送http請求。你也說「如果我沒有設置代理,那麼程序工作」 - 所以......不要設置代理並享受工作程序!! ?? !!? – Vorsprung

回答

3

問題出在已關閉的端口。 我不得不在技術支持打開我需要的端口之前購買專用IP。

現在我的腳本工作正常。

結論:當你在一個共享主機,大多數端口可能已關閉,你將不得不聯繫技術支持來打開端口。

相關問題