urllib2可以抓取網頁,爲了模擬瀏覽器需要增加如下header:
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:gzip,deflate,sdch
Accept-Language:zh,en-US;q=0.8,en;q=0.6
Connection:keep-alive
Host:www.baidu.com
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/37.0.2062.120 Chrome/37.0.2062.120 Safari/537.36
把header作爲一個dict傳參數,但是由於請求gzip,所以需要對返回結果進行解壓,或者就不進行http gzip請求
from StringIO import StringIO
import gzip
req = urllib2.Request(url, headers=headers)
resp = urllib2.urlopen(req)
content = ''
# handle gzip compress
# 這裏需要注意,因爲模擬chrome的請求,所以返回的是gzip格式的編碼,而urllib2是不會自動處理編碼的,需要用StringIO和gzip來協助處理,得到解壓後的串
#否則會報錯:UnicodeDecodeError: 'utf8' codec can't decode byte 0x8b in position 1: invalid start byte
if resp.info().get('Content-Encoding') == 'gzip':
buf = StringIO(resp.read())
f = gzip.GzipFile(fileobj=buf)
content = f.read()
else :
content = resp.read()
# 這裏根據網頁返回的實際charset進行unicode編碼
encoding = resp.headers['content-type'].split('charset=')[-1]
ucontent = unicode(content, encoding)
</pre><pre code_snippet_id="505001" snippet_file_name="blog_20141102_8_3978368" name="code" class="python">參考:
http://stackoverflow.com/questions/3947120/does-python-urllib2-automatically-uncompress-gzip-data-fetched-from-webpage
</pre><pre code_snippet_id="505001" snippet_file_name="blog_20141102_11_1775350" name="code" class="python">