2009-04-19 46 views
10

我已經在使用cookie和POST/GET的python中編寫了一個腳本。我還在腳本中包含了代理支持。但是,當進入死代理服務器時,腳本崩潰。在運行我的腳本的其餘部分之前,有什麼方法可以檢查代理是否死/活?代理簽入python

此外,我注意到一些代理不能正確處理cookie/POST頭。有沒有什麼辦法解決這一問題?

+0

你就不能捕獲異常? – marcog 2009-04-19 12:08:48

+0

我認爲捕捉異常並不是最好的方式,檢查我在dbr回答中留下的評論。你能給我你的意見嗎?因爲我打算自己編寫代理檢查器(即時只是從python開始,這將是我的第二個python腳本)。 – jahmax 2010-08-01 00:49:17

回答

13

最簡單的是就是簡單地從urllib的捕捉IOError異常:

try: 
    urllib.urlopen(
     "http://example.com", 
     proxies={'http':'http://example.com:8080'} 
    ) 
except IOError: 
    print "Connection error! (Check proxy)" 
else: 
    print "All was fine" 

此外,從this blog post - "check status proxy address"(稍作改進):

import urllib2 
import socket 

def is_bad_proxy(pip):  
    try: 
     proxy_handler = urllib2.ProxyHandler({'http': pip}) 
     opener = urllib2.build_opener(proxy_handler) 
     opener.addheaders = [('User-agent', 'Mozilla/5.0')] 
     urllib2.install_opener(opener) 
     req=urllib2.Request('http://www.example.com') # change the URL to test here 
     sock=urllib2.urlopen(req) 
    except urllib2.HTTPError, e: 
     print 'Error code: ', e.code 
     return e.code 
    except Exception, detail: 
     print "ERROR:", detail 
     return True 
    return False 

def main(): 
    socket.setdefaulttimeout(120) 

    # two sample proxy IPs 
    proxyList = ['125.76.226.9:80', '213.55.87.162:6588'] 

    for currentProxy in proxyList: 
     if is_bad_proxy(currentProxy): 
      print "Bad Proxy %s" % (currentProxy) 
     else: 
      print "%s is working" % (currentProxy) 

if __name__ == '__main__': 
    main() 

記住這可能會增加一倍的時間腳本需要,如果代理服務器停機(因爲您將不得不等待兩個連接超時)。除非您特別必須知道代理服務器出現故障,否則處理IOError會更簡潔,更簡單,更快速。

+1

但是一些代理可以連接到url,但是他們並沒有從那個url打開實際的html,他們顯示了一個自定義的錯誤,所以你不能在那裏發現異常,在req中檢查字符串會更好。讀()? – jahmax 2010-08-01 00:37:41

1

我認爲更好的方法就像dbr說的那樣,處理異常。

,可能是在某些情況下更好的另一種解決方案是使用外部online proxy checker工具來檢查,如果代理服務器是活着,然後繼續使用您的腳本不作任何修改。

0

有一個包裝精美Grab 所以,如果對你合適,你可以寫這樣的事情(簡單有效的代理檢查發電機):

from grab import Grab, GrabError 

def get_valid_proxy(proxy_list): #format of items e.g. '128.2.198.188:3124' 
    g = Grab() 
    for proxy in proxy_list: 
     g.setup(proxy=proxy, proxy_type='http', connect_timeout=5, timeout=5) 
     try: 
      g.go('google.com') 
     except GrabError: 
      #logging.info("Test error") 
      pass 
     else: 
      yield proxy