利用Python urllib庫爬取網(wǎng)頁,有時獲得的網(wǎng)頁打印或?qū)懳募龅骄幋a問題,找了許久終于知道為什么了。
首先利用urlopen()函數(shù)獲取網(wǎng)頁對象,再利用info()函數(shù)打印網(wǎng)頁的相關(guān)信息,確定網(wǎng)頁的編碼及是否壓縮。
- import urllib.request
-
- fp = urllib.request.urlopen('http://www.sina.com')
- mybytes = fp.read()
- text = mybytes.decode('utf8')
- print(text)
報錯
顯示編碼錯誤,剛開始,傻傻地試各種編碼,utf-8,gbk,gb2312,都不行,心里堵得慌,是在玩我嗎?
so,開始懷疑是bug,但是有的網(wǎng)頁又不會出錯,這就奇怪了,最后google找到了一個解釋,說是返回的網(wǎng)頁數(shù)據(jù)是壓縮格式,恍然大悟,先打印網(wǎng)頁信息,看一眼
gzip,網(wǎng)頁是壓縮后的,所以要先解壓,上代碼
- import urllib.request
- import zlib
-
- fp = urllib.request.urlopen('http://www.sina.com')
- mybytes = fp.read()
- decompressed_data = zlib.decompress(mybytes ,16+zlib.MAX_WBITS)
- text = decompressed_data.decode('utf8')
- print(text)
- print(fp.info())
結(jié)果
Google問題原版
http://stackoverflow.com/questions/3746993/change-python-byte-type-to-string
http://stackoverflow.com/questions/3703276/how-to-tell-if-a-file-is-gzip-compressed/3703300#3703300
本站僅提供存儲服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請
點(diǎn)擊舉報。