1. 程式人生 > >Python 爬蟲IP代理

Python 爬蟲IP代理

想必大家在寫爬蟲都有遇到過這樣的錯誤:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte

經過查詢各大論壇發現原來是該網站對網頁進行了壓縮,所以你爬取的網頁其實是個為解壓的網頁

所以我們需要進行解壓。當然我們首先需要看看網站到底是解壓還是為解壓過的,進行步驟如下:

使用urllib.request.urlopen().info()檢視:顯現資訊如下:

Server: nginx/1.6.2
Date: Thu, 15 Jun 2017 03:24:02 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 3595
Connection: close
Vary: Accept-Encoding
Content-Encoding: gzip


Set-Cookie: channelid=0; Path=/
Set-Cookie: sid=1497496689230807; Path=/

Content-Encoding: gzip 這句說明網站進行了壓縮


解壓步驟如下:

我們需要匯入 gzip以及io模組:

1:先將爬取的物件進行二進位制的轉換 使用io.BytesIO(‘爬取的物件’)

2:進行解壓gzip.GzipFile(‘轉換的二進位制’)

這樣我們爬取的網站就解壓完成不會報錯了!!!!!

我寫的爬蟲程式碼:
import urllib.request
import re,gzip,io

def open_url(url):
    req = urllib.request.Request(url)
    req.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36')
    response = urllib.request.urlopen(req)
    
    print(response.info())
    ###判斷是否壓縮
    if response.info().get('Content-Encoding') == 'gzip':
        buf = io.BytesIO(response.read())
        gzip_f = gzip.GzipFile(fileobj=buf)###進行解壓
        content = gzip_f.read()
    else:
        content = response.read()
       
    return content.decode('utf-8')

def get_img(html):
    p = r'<td data-title="IP">(.+)<'
    imglist = re.findall(p,html)
    print(imglist)


if __name__ == '__main__':
    url="http://www.kuaidaili.com/free/"
    get_img(open_url(url))




本文講解的更多的是錯誤處理....



d攝氏度