一、lxml模塊介紹及安裝,Xpath語言了解
1. lxml模塊是python爬蟲中的一個解析器,Xpath是一門在xml文檔中根據節點查找信息的語言。
可以參考菜鳥聯盟學習xpath
2. 安裝 pip install lxml
3.網頁知識了解xpath節點及常用提取屬性
標簽: div ul li a table tr td th p span
節點: 樹形結構 父 子 同胞 先輩 后代
提取數據常用的屬性:標簽/text()
a標簽:文本提取a/text() 超鏈接(也就是跳轉的url) 提取a/href
二、
lxml模塊下的xpath解析提取
將html源碼轉換為element html對象,變量selector
from lxml import etree
selector=etree.HTML(網頁源碼)
數據變量1=selector.xpat('xpath表達式')
from lxml import etree
file=open('/Users/shixin/Downloads/10-lxml模塊及xpath解析/10-lxml模塊及xpath解析/xpath.html','r',encoding='utf-8')
html = file.read()
#print(html) #獲取的HTML
selector = etree.HTML(html)
#獲取title
title = selector.xpath('//title/text()')[0]
print(title)
h1 = selector.xpath('//h1/text()')[0].strip() #列表索引 然后去除空格
print(h1)
haha= selector.xpath('//div[@class="works"]/text()') #class前加@
print(haha)
WX20170830-143312@2x.png
結構化提取(for循環,變量xpath的寫法):
infos=selector.xpath('//a')
print(len(infos))
for info in infos:
a_text=info.xpath('text()')[0]
a_href=info.xpath('@href')[0]
print(a_text,a_href)
WX20170830-145209@2x.png
練習
一、div標簽文本提取
將學習視頻中xpath.html文件中div標簽下文本值
“第一個div” ,“第二個div” 使用xpath結構化提取并打印輸出
二、ul標簽文本提取
將xpath.html文件中ul標簽下“流程” ,“xpath學習”,“流程2”文本值
使用xpath結構化提取并打印輸出
三、過濾標簽
將xpath.html文件中的第一個div下的前3個a標簽的文本及超鏈接
使用xpath結構化提取,打印輸出
四、requests模塊和lxml&xpath結合提取數據
結合上節課requests模塊知識,將陽光電影網導航欄的文本及超鏈接結構化提取
divs=selector.xpath('//div[@class="works"]/text()')
print(divs)
uls=selector.xpath('//ul/text()')
print(uls)
infos2=selector.xpath('//div[@class="works"][1]/ul[@class="title"][1]/li[position()<4]/a')
for infos2 in infos2:
a_text = infos2.xpath('text()')[0]
a_href=infos2.xpath('@href')[0]
print(a_text,a_href)
WX20170830-151227@2x.png