[踩坑]python實現並行爬蟲,python爬蟲
問題背景:指定爬蟲depth、線程數, python實現並行爬蟲
思路: 單線程 實現爬蟲類Fetcher
多線程 threading.Thread去調Fetcher
方法:Fetcher 中,用urllib.urlopen開啟指定url,讀取資訊:
response = urllib.urlopen(self.url)content = response.read()
但是這樣有問題, 比如對於www.sina.com來說,讀出來的content是亂碼的:
>>> content[0:100]'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03\xec\xbdk\x93\x1c\xd7u \xf8\x99\x8c\xd0\x7fH\x14W\xe8*t=2\xeb\xd5\xd5]H`\x014@4\x88\x97\x00\xf0%\x10\xea\xc8\xaa\xca\xeeN\xa0\xba\xb2X\x99\x85\x06X\xa8\x1fCj\x1c\xb6ly-\x92\x06\xf5 %\xca"E\xf1!R\x94\xa8\x87C3\x9e\xf1\xd8#\x87\xbd;\x8e\xd8\x99\x8d\xb1\x1d\xf2'
於是用了python第三方工具chardet,通過
chardet.detect(content)
進行content中字元集的檢測:
>>> chardet.detect(content){'confidence': 0.99, 'encoding': 'GB2312'}
好,問題解決了:
>>> import urllib>>> url = 'http://www.sina.com'>>> response = urllib.urlopen(url)>>> content = response.read()>>> chardet.detect(content){'confidence': 0.99, 'encoding': 'GB2312'}
但是我們想高效爬蟲的時候需要設定urlopen的timeout時間,這在urllib中沒有實現,而在urllib2中有實現:
response = urllib2.urlopen(self.url, timeout = self.timeout)
但是這時候再用chardet出現的字元集結果與上次不同:
>>> import urllib>>> url = 'http://www.sina.com'>>> response = urllib2.urlopen(url, timeout=1)>>> content = response.read()>>> chardet.detect(content){'confidence': 0.0, 'encoding': None}
這是怎麼回事? 原來是這個頁面的編碼問題, 該頁面返回的是gzip編碼,參考<python urllib2 returns garbage - Stack Overflow>
實際上每次應該判斷頁面資訊的'Content-Encoding'是否為'gzip'。
urllib支援gzip頁面自動解壓而urllib2不支援。 所以對於這種頁面, 先解壓再read:
try: response = urllib2.urlopen(self.url, timeout = self.timeout) if response.info().get('Content-Encoding', "") == 'gzip': #e.g www.sina.com.cn buf = StringIO.StringIO(response.read()) f = gzip.GzipFile(fileobj=buf) content = f.read() else: content = response.read() content = self.enc_dec(content) return contentexcept socket.timeout: log.warn("Timeout in fetching %s" % self.url)
到這裡,大家是不是都以為我只是個標題黨。。。?
*******************************************************************************
那麼,就把調通的整個spider檔案share一下吧,
程式支援多線程爬蟲,主檔案為spider.py, testSpider.py為單測(不保證覆蓋率)。
程式地址:http://download.csdn.net/detail/abcjennifer/9086751
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。