XPath語法和lxml模塊
XPath
lxml庫
1.什么是XPath?
XPath (XML Path Language) 是一門在 XML 文檔中查找信息的語言,可用來在 XML 文檔中對元素和屬性進行遍歷。
W3School官方文檔:http://www.w3school.com.cn/xpath/index.asp
2.XPath 開發工具
- 開源的XPath表達式編輯工具:XMLQuire(XML格式文件可用)
- Chrome插件 XPath Helper
- Firefox插件 XPath Checker
3.Chrome中安裝XPath 開發工具不能使用
解決方法:參考https://blog.csdn.net/Cayny/article/details/81396711
1.重啟瀏覽器,快捷鍵CTRL+SHIFT+X開啟XPath Helper插件;
2.長按CTRL+SHIFT,鼠標指向需提取的段落,按X開啟或關閉提取,提取到的段落會變為黃色。
4.選取節點
XPath 使用路徑表達式來選取 XML 文檔中的節點或者節點集。這些路徑表達式和我們在常規的電腦文件系統中看到的表達式非常相似。
下面列出了最常用的路徑表達式:
表達式 | 描述 |
---|---|
nodename | 選取此節點的所有子節點。 |
/ | 從根節點選取。 |
// | 從匹配選擇的當前節點選擇文檔中的節點,而不考慮它們的位置。 |
. | 選取當前節點。 |
.. | 選取當前節點的父節點。 |
@ | 選取屬性。 |
在下面的表格中,我們已列出了一些路徑表達式以及表達式的結果:
路徑表達式 | 結果 | |
---|---|---|
bookstore | 選取 bookstore 元素的所有子節點。 | |
/bookstore | 選取根元素 bookstore。注釋:假如路徑起始於正斜杠( / ),則此路徑始終代表到某元素的絕對路徑! | |
bookstore/book | 選取屬於 bookstore 的子元素的所有 book 元素。 | |
//book | 選取所有 book 子元素,而不管它們在文檔中的位置。 | |
bookstore//book | 選擇屬於 bookstore 元素的后代的所有 book 元素,而不管它們位於 bookstore 之下的什么位置。 | |
//@lang | 選取名為 lang 的所有屬性。 |
5.謂語(Predicates)
謂語用來查找某個特定的節點或者包含某個指定的值的節點,被嵌在方括號中。
在下面的表格中,我們列出了帶有謂語的一些路徑表達式,以及表達式的結果:
路徑表達式 | 結果 |
---|---|
/bookstore/book[1] | 選取屬於 bookstore 子元素的第一個 book 元素。 |
/bookstore/book[last()] | 選取屬於 bookstore 子元素的最后一個 book 元素。 |
/bookstore/book[last()-1] | 選取屬於 bookstore 子元素的倒數第二個 book 元素。 |
/bookstore/book[position()<3] | 選取最前面的兩個屬於 bookstore 元素的子元素的 book 元素。 |
//title[@lang] | 選取所有擁有名為 lang 的屬性的 title 元素。 |
//title[@lang=’eng’] | 選取所有 title 元素,且這些元素擁有值為 eng 的 lang 屬性。 |
/bookstore/book[price>35.00] | 選取 bookstore 元素的所有 book 元素,且其中的 price 元素的值須大於 35.00。 |
/bookstore/book[price>35.00]/title | 選取 bookstore 元素中的 book 元素的所有 title 元素,且其中的 price 元素的值須大於 35.00。 |
//div[contains(@class,"f1")] | 選擇div屬性包含"f1"的元素 |
6.選取未知節點
XPath 通配符可用來選取未知的 XML 元素。
通配符 | 描述 |
---|---|
* | 匹配任何元素節點。 |
@* | 匹配任何屬性節點。 |
node() | 匹配任何類型的節點。 |
在下面的表格中,我們列出了一些路徑表達式,以及這些表達式的結果:
路徑表達式 | 結果 |
---|---|
/bookstore/* | 選取 bookstore 元素的所有子元素。 |
//* | 選取文檔中的所有元素。 |
html/node()/meta/@* | 選擇html下面任意節點下的meta節點的所有屬性 |
//title[@*] | 選取所有帶有屬性的 title 元素。 |
7.選取若干路徑
通過在路徑表達式中使用“|”運算符,您可以選取若干個路徑。
實例
在下面的表格中,我們列出了一些路徑表達式,以及這些表達式的結果:
路徑表達式 | 結果 |
---|---|
//book/title | //book/price | 選取 book 元素的所有 title 和 price 元素。 |
//title | //price | 選取文檔中的所有 title 和 price 元素。 |
/bookstore/book/title | //price | 選取屬於 bookstore 元素的 book 元素的所有 title 元素,以及文檔中所有的 price 元素。 |
8.XPath的運算符
下面列出了可用在 XPath 表達式中的運算符:
這些就是XPath的語法內容,在運用到Python抓取時要先轉換為xml。
lxml庫
lxml 是 一個HTML/XML的解析器,主要的功能是如何解析和提取 HTML/XML 數據。
lxml和正則一樣,也是用 C 實現的,是一款高性能的 Python HTML/XML 解析器,我們可以利用之前學習的XPath語法,來快速的定位特定元素以及節點信息。
lxml python 官方文檔:http://lxml.de/index.html
需要安裝C語言庫,可使用 pip 安裝:
pip install lxml
(或通過wheel方式安裝)
1.lxml簡單使用
.xpath() 返回值是一個列表,取值時需要注意
#encoding: utf-8 # 導入etree時需要手動,不會有提示 from lxml import etree text = """ <table class="tablelist" cellpadding="0" cellspacing="0"> <tbody> <tr class="h"> <td class="l" width="374">職位名稱</td> <td>職位類別</td> <td>人數</td> <td>地點</td> <td>發布時間</td> </tr> <tr class="even"> <td class="l square"><a target="_blank" href="position_detail.php?id=33824&keywords=python&tid=87&lid=2218">22989-金融雲區塊鏈高級研發工程師(深圳)</a></td> <td>技術類</td> <td>1</td> <td>深圳</td> <td>2017-11-25</td> </tr> """ # 從字符串中讀取 def parse_text(): htmlElement = etree.HTML(text) print(etree.tostring(htmlElement,encoding='utf-8').decode("utf-8")) # 從文件中讀取html代碼 def parse_tencent_file(): htmlElement = etree.parse("tencent.html") print(etree.tostring(htmlElement, encoding='utf-8').decode('utf-8')) # 解析html,指定解析器,有時候html代碼不規范需要指定解析器 def parse_lagou_file(): # 指定解析器 parser = etree.HTMLParser(encoding='utf-8') htmlElement = etree.parse("lagou.html",parser=parser) print(etree.tostring(htmlElement, encoding='utf-8').decode('utf-8')) if __name__ == '__main__': parse_text() # parse_file() # parse_lagou_file()
2.lxml和xpath結合使用
from lxml import etree # 1. 獲取所有tr標簽 # 2. 獲取第2個tr標簽 # 3. 獲取所有class等於even的tr標簽 # 4. 獲取所有a標簽的href屬性 # 5. 獲取所有的職位信息(純文本) parser = etree.HTMLParser(encoding='utf-8') html = etree.parse("tencent.html",parser=parser) # 1. 獲取所有tr標簽 # //tr # xpath函數返回的是一個列表 # trs = html.xpath("//tr") # for tr in trs: # print(etree.tostring(tr,encoding='utf-8').decode("utf-8")) # 2. 獲取第2個tr標簽 # tr = html.xpath("//tr[2]")[0] # print(etree.tostring(tr,encoding='utf-8').decode("utf-8")) # 3. 獲取所有class等於even的tr標簽 # trs = html.xpath("//tr[@class='even']") # for tr in trs: # print(etree.tostring(tr,encoding='utf-8').decode("utf-8")) # 4. 獲取所有a標簽的href屬性 # aList = html.xpath("//a/@href") # for a in aList: # print("http://hr.tencent.com/"+a) # 5. 獲取所有的職位信息(純文本) trs = html.xpath("//tr[position()>1]") positions = [] for tr in trs: # 在某個標簽下,再執行xpath函數,獲取這個標簽下的子孫元素 # 那么應該在//之前加一個點,代表是在當前元素下獲取 href = tr.xpath(".//a/@href")[0] fullurl = 'http://hr.tencent.com/' + href title = tr.xpath("./td[1]//text()")[0] category = tr.xpath("./td[2]/text()")[0] nums = tr.xpath("./td[3]/text()")[0] address = tr.xpath("./td[4]/text()")[0] pubtime = tr.xpath("./td[5]/text()")[0] position = { 'url': fullurl, 'title': title, 'category': category, 'nums': nums, 'address': address, 'pubtime': pubtime } positions.append(position) print(positions)
注意:

## lxml結合xpath注意事項: 1. 使用`xpath`語法。應該使用`Element.xpath`方法。來執行xpath的選擇。示例代碼如下: ```python trs = html.xpath("//tr[position()>1]") ``` `xpath函數`返回來的永遠是一個列表。 2. 獲取某個標簽的屬性: ```python href = html.xpath("//a/@href") # 獲取a標簽的href屬性對應的值 ``` 3. 獲取文本,是通過`xpath`中的`text()`函數。示例代碼如下: ```python address = tr.xpath("./td[4]/text()")[0] ``` 4. 在某個標簽下,再執行xpath函數,獲取這個標簽下的子孫元素,那么應該在斜杠之前加一個點,代表是在當前元素下獲取。示例代碼如下: ```python address = tr.xpath("./td[4]/text()")[0] 5.xpath解析器下元素下標從1開始