(一) 三種網頁抓取方法
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