本博客內容來自韋瑋老師網絡爬蟲課堂筆記,僅用於個人學習和複習,請勿轉載用於其他商業用途。
Urllib庫(一)
一個簡單的小作業
將https://read.douban.com/provider/all網址中所有的出版社信息都爬取出來。網站圖片如下:
可以看到,網頁中有許多的出版社。下面我們用代碼將所有出版社的名字爬取出來,並保存在文件中。
import urllib.request
import re
url = "http://read.douban.com/provider/all"
data = urllib.request.urlopen(url).read()
data = data.decode("utf-8")
pat = '<div class="name">(.*?)</div>'
mydata = re.compile(pat).findall(data) #生成了一個列表
fh = open("D:/PROGRAMMING/數據分析/Python數據分析與挖掘實戰視頻教程/實驗/test.txt", "w")
for i in range(0, len(mydata)):
fh.write(mydata[i] + "\n")
fh.close()
運行後,我們來看一下結果:
嗯,很成功……
1、urllib.request.urlretrive()
可以將目標網頁一次性爬到本地。我們試一下將計算機二級考試的官網爬取到本地:
import urllib.request
urllib.request.urlretrieve("http://ncre.neea.edu.cn/", filename="D:/PROGRAMMING/數據分析/Python數據分析與挖掘實戰視頻教程/實驗/1.html")
查看爬到的網頁,大概長這個樣子:
2、urllib.request.urlclenup()
使用該函數,可以清除緩存
3、urllib.request.info()
可以瞭解當前環境的信息,實例如下:
file = urllib.request.urlopen("http://ncre.neea.edu.cn/")
print(file.info())
#
Server: OPTIMUS/1.11.2.4_21
Date: Sat, 16 Nov 2019 10:46:45 GMT
Content-Type: text/html
Content-Length: 21514
Connection: close
Last-Modified: Mon, 11 Nov 2019 06:29:56 GMT
ETag: "5dc8ffe4-540a"
Accept-Ranges: bytes
Age: 2061
Via: http/1.1 CT-CMC-CNC-SDJN-P-118-113 (DLC-6.1.26), http/1.1 CT-SDZZ-C-88-17 (DLC-6.1.26)
Server-Info: DnionATS
HitType: TCP_MEM_HIT
4、urllib.request.getcode()
獲取當前爬取網頁的狀態碼,不同的狀態碼代表不同的信息。
file = urllib.request.urlopen("http://ncre.neea.edu.cn/")
print(file.getcode())
#
200
5、urllib.request.geturl()
獲得當去爬取網站的網址。
print(file.geturl())
#
http://ncre.neea.edu.cn/
由於網絡速度或服務器的問題,當我們訪問一個網站,如果網頁長時間未響應,系統會判斷該網頁超時,無法打開網頁。但是有的時候我們需要根據自己的需要來設置超時的時長。比如我們希望2秒鐘沒有反應,及判斷爲超時,那麼timeout的值就是2。
舉例:
file = urllib.request.urlopen("http://ncre.neea.edu.cn/", timeout=1)
使用Python的IDLE執行,會報錯,因爲這個網站服務器不夠強因此很難在1秒鐘以內做出反應。如果有些網站的服務器比較差,我們可以將timeout的值設置的大一些。
下面我們多次訪問一個網站,將網頁進行讀取,計算網頁字符的長度,timeout設置爲0.5秒。如果正常爬取,則輸出字符長度,如果出現異常,輸出異常原因:
for i in range(0, 100):
try:
file = urllib.request.urlopen("http://yum.iqianyue.com",timeout=0.5)
data = file.read()
print(len(data))
except Exception as e:
print("出現異常:" + str(e))
#
14165
14165
14165
14165
14165
出現異常:<urlopen error timed out>
14165
14165
...
略