1. 程式人生 > >python爬蟲(一)Urllib使用

python爬蟲(一)Urllib使用

爬蟲介紹

網路爬蟲就是一個爬行程式,一個抓取網頁的程式。網路爬蟲的基本操作是抓取網頁,但爬蟲概念包括抓取和資料解析兩個部分。
爬蟲是通過網頁的連結地址來尋找網頁的。從網站某一個頁面(通常是首頁)開始,讀取網頁的內容,找到在網頁中的其它連結地址,然後通過這些連結地址尋找下一個網頁,這樣一直迴圈下去,直到把這個網站所有的網頁都抓取完為止。

爬蟲意義

爬蟲可以完成很多事情,如:

  • 爬取靜態頁面
  • 分析並推送價值資料
  • 資源的批量下載
  • 各類資料監控
  • 社會計算的統計預測
  • 機器翻譯語料庫
  • 機器學習訓練庫

Urllib庫

Urllib提供了基礎的python爬蟲爬取操作,我們可以使用Urllib庫完成簡單的資料請求和網頁資訊抓取。

簡單的資料請求

import urllib.request

response=urllib.request.urlopen('https://www.baidu.com')
print(response.read().decode('utf-8'))

帶引數的資料請求

import urllib.request as url_req
import urllib.parse as url_pa

data=url_pa.urlencode({'query':'ai'})
url='https://www.sogou.com/web?'

request = url_req.Request(url)
#引數需要轉為流的形式做傳遞
response = url_req.urlopen(request,data.encode('utf-8')) print(response.read().decode('utf-8'))

攜帶header資訊的迴圈資料請求

import urllib.parse
import time

headers = {
    'Host': 'www.budejie.com',
    'Referer': 'http://www.budejie.com',
    'User_agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'
} for i in range(1, 6): req = urllib.request.Request('http://www.budejie.com/' + str(i), headers=headers) res = urllib.request.urlopen(req) html = res.read().decode('utf-8') with open('get/' + str(i) + '.html', 'w', encoding='utf-8') as f: f.write(html) time.sleep(3) print('第%d頁,長度%d' % (i, len(html))) headers['referer'] = 'http://www.budejie.com/' + str(i)

通過代理髮起請求

import urllib.request

req = urllib.request.Request('https://www.baidu.com')
proxy={'http':'119.29.12.129'}
proxy_handler=urllib.request.ProxyHandler(proxy)
#順手設定一個debug級別日誌
http_handler=urllib.request.HTTPHandler(debuglevel=1)
opener=urllib.request.build_opener(proxy_handler, http_handler)
response=opener.open('http://www.baidu.com')
print(len(response.read().decode('utf-8')))

請求異常捕獲

請求中常見的異常有兩類,URLError與HTTPError

urllib.error.URLError

URLError通常與環境有關,具體原因如下:

  • 網路無連線,本機無法上網
  • 無法正常連線到伺服器
  • 伺服器不存在,域名無法解析

urllib.error.HTTPError

HTTPError是URLError的子類,當請求順利接收到伺服器返回的響應且狀態碼異常時,會丟擲該錯誤

異常捕獲邏輯

由於兩者存在父子關係,按照慣例應首先捕獲子類異常,捕獲邏輯如下

import urllib.request
import urllib.error
req = urllib.request.Request('http://www.douyu.com/Jack_Cui.html')
try:
    print(urllib.request.urlopen(req).read().decode('utf-8'))
except urllib.error.HTTPError as e:
    print(e.reason)
    print(e.code)
except urllib.error.URLError as e:
    print(e.reason)
else:
    print('ok')