Python網絡爬蟲筆記(一):網頁抓取方式和LXML示例


(一)   三種網頁抓取方法

1、    正則表達式:

模塊使用C語言編寫,速度快,但是很脆弱,可能網頁更新后就不能用了。

2、    Beautiful Soup

模塊使用Python編寫,速度慢。

安裝:

pip install beautifulsoup4

3、    Lxml

模塊使用C語言編寫,即快速又健壯,通常應該是最好的選擇。

(二)   Lxml安裝

pip install lxml

如果使用lxml的css選擇器,還要安裝下面的模塊

pip install cssselect

(三)   使用lxml示例

 1 import urllib.request as re
 2 import lxml.html
 3 #下載網頁並返回HTML
 4 def download(url,user_agent='Socrates',num=2):
 5     print('下載:'+url)
 6     #設置用戶代理
 7     headers = {'user_agent':user_agent}
 8     request = re.Request(url,headers=headers)
 9     try:
10         #下載網頁
11         html = re.urlopen(request).read()
12     except re.URLError as e:
13         print('下載失敗'+e.reason)
14         html=None
15         if num>0:
16             #遇到5XX錯誤時,遞歸調用自身重試下載,最多重復2次
17             if hasattr(e,'code') and 500<=e.code<600:
18                 return download(url,num=num-1)
19     return html
20 html = download('https://tieba.baidu.com/p/5475267611')
21 #將HTML解析為統一的格式
22 tree = lxml.html.fromstring(html)
23 # img = tree.cssselect('img.BDE_Image')
24 #通過lxml的xpath獲取src屬性的值,返回一個列表
25 img = tree.xpath('//img[@class="BDE_Image"]/@src')
26 x= 0
27 #迭代列表img,將圖片保存在當前目錄下
28 for i in img:
29     re.urlretrieve(i,'%s.jpg'%x)
30     x += 1

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM