1. 程式人生 > >python爬蟲urllib庫使用

python爬蟲urllib庫使用

urllib包括以下四個模組:

  1.request:基本的HTTP請求模組,可以用來模擬傳送請求。就像在瀏覽器裡輸入網址然後回車一樣,只需要給庫方法傳入URL以及額外的引數,就可以模擬實現這個過程。

  2.error:異常處理模組

  3.parse:提供了許多URL處理方法,如拆分、解析、合併等

  4.robotparser:主要用來識別網站的robots.txt檔案,判斷哪些網站可以爬(很少用)

1.1傳送請求

  1urlopen()

import urllib.request
response = urllib.request.urlopen('https://baike.baidu.com/item/csdn/172150?fr=aladdin
') print(response.read().decode('UTF-8')) #read()返回網頁內容

結果:

#檢視返回型別
import
urllib.request response = urllib.request.urlopen('https://baike.baidu.com/item/csdn/172150?fr=aladdin') print(type(response))

status屬性

import urllib.request
response = urllib.request.urlopen('https://baike.baidu.com/item/csdn/172150?fr=aladdin
') print(response.status) print(response.getheaders()) print(response.getheader('Server'))