什么是XPath?
XPath (XML Path Language) 是一門在 XML 文檔中查找信息的語言,可用來在 XML 文檔中對元素和屬性進行遍歷。
W3School官方文檔:http://www.w3school.com.cn/xpath/index.asp
XPath 開發工具
- 開源的XPath表達式編輯工具:XMLQuire(XML格式文件可用)
- Chrome插件 XPath Helper
- Firefox插件 XPath Checker
選取節點
XPath 使用路徑表達式來選取 XML 文檔中的節點或者節點集。這些路徑表達式和我們在常規的電腦文件系統中看到的表達式非常相似。
下面列出了最常用的路徑表達式:
表達式 | 描述 |
---|---|
nodename | 選取此節點的所有子節點。 |
/ | 從根節點選取。 |
// | 從匹配選擇的當前節點選擇文檔中的節點,而不考慮它們的位置。 |
. | 選取當前節點。 |
.. | 選取當前節點的父節點。 |
@ | 選取屬性。 |
在下面的表格中,我們已列出了一些路徑表達式以及表達式的結果:
路徑表達式 | 結果 | |
---|---|---|
bookstore | 選取 bookstore 元素的所有子節點。 | |
/bookstore | 選取根元素 bookstore。注釋:假如路徑起始於正斜杠( / ),則此路徑始終代表到某元素的絕對路徑! | |
bookstore/book | 選取屬於 bookstore 的子元素的所有 book 元素。 | |
//book | 選取所有 book 子元素,而不管它們在文檔中的位置。 | |
bookstore//book | 選擇屬於 bookstore 元素的后代的所有 book 元素,而不管它們位於 bookstore 之下的什么位置。 | |
//@lang | 選取名為 lang 的所有屬性。 |
謂語(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。 |
選取未知節點
XPath 通配符可用來選取未知的 XML 元素。
通配符 | 描述 |
---|---|
* | 匹配任何元素節點。 |
@* | 匹配任何屬性節點。 |
node() | 匹配任何類型的節點。 |
在下面的表格中,我們列出了一些路徑表達式,以及這些表達式的結果:
路徑表達式 | 結果 |
---|---|
/bookstore/* | 選取 bookstore 元素的所有子元素。 |
//* | 選取文檔中的所有元素。 |
//title[@*] | 選取所有帶有屬性的 title 元素。 |
選取若干路徑
通過在路徑表達式中使用“|”運算符,您可以選取若干個路徑。
實例
在下面的表格中,我們列出了一些路徑表達式,以及這些表達式的結果:
路徑表達式 | 結果 |
---|---|
//book/title | //book/price | 選取 book 元素的所有 title 和 price 元素。 |
//title | //price | 選取文檔中的所有 title 和 price 元素。 |
/bookstore/book/title | //price | 選取屬於 bookstore 元素的 book 元素的所有 title 元素,以及文檔中所有的 price 元素。 |
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方式安裝)
初步使用
我們利用它來解析 HTML 代碼,示例1----------使用xpath的爬蟲:
1 from urllib import request 2 import urllib.parse 3 from lxml import etree 4 5 #根據url發送請求,獲取服務器響應文件 6 def loadPage(url): 7 # header = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36"} 8 9 a=request.Request(url) # 奇怪,xpath無法解析出內容,結果為空。把headers去掉就好了,不知道為什么。 10 response=request.urlopen(a).read().decode('utf-8') 11 # print(response) 12 13 # 解析HTML文檔為HTML DOM模型 14 content=etree.HTML(response) 15 # 返回所有匹配成功的列表集合 16 link_list=content.xpath("//div[@class='t_con cleafix']/div[2]/div/div[1]/a/@href") 17 # print(link_list) 18 19 for link in link_list: 20 print('正在獲取url鏈接....') 21 fulllink = "http://tieba.baidu.com"+link # 組合為每個帖子的鏈接 22 loadImage(fulllink) 23 24 25 # 取出每個帖子里的每個圖片連接 26 def loadImage(link): 27 header = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36"} 28 b=request.Request(link,headers=header) 29 response=request.urlopen(b).read().decode('utf-8') 30 31 # 取出帖子里每層層主發送的圖片連接集合 32 content1=etree.HTML(response) 33 link_list=content1.xpath("//img[@class='BDE_Image']/@src") 34 # print(link_list) 35 36 for link in link_list: 37 print('正在獲取圖片鏈接....') 38 wirteImage(link) # 取出每個圖片的連接 39 40 41 #將圖片寫入到本地 42 def wirteImage(link): 43 header = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36"} 44 c = request.Request(link, headers=header) 45 image = request.urlopen(c).read() # 圖片原始數據 46 # print(image) 47 filname=link[-10:] # 取出連接后10位做為文件名 48 print('正在保存圖片....') 49 with open(r'E:\python_practice_ku\pachong\1\\'+filname,'wb') as f: 50 f.write(image) 51 52 53 #貼吧爬蟲調度器,負責組合處理每個頁面的url 54 def tiebaSpider(url,kw, beginPage, endPage): 55 data = {'kw': kw} 56 data = urllib.parse.urlencode(data) 57 58 for page in range(beginPage,endPage+1): 59 fullurl = url + data+"&ie=utf-8" + "&pn=" +str(page) 60 loadPage(fullurl) 61 62 63 if __name__ == '__main__': 64 kw = input("請輸入需要爬取的貼吧名:") 65 beginPage = int(input("請輸入起始頁:")) 66 endPage = int(input("請輸入結束頁:")) 67 68 url = 'https://tieba.baidu.com/f?' 69 tiebaSpider(url,kw,beginPage,endPage)
示例2
1 from urllib import request 2 from lxml import etree 3 import json 4 5 url='http://www.waduanzi.com/' 6 header={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36"} 7 8 a=request.Request(url,headers=header) 9 response=request.urlopen(a).read().decode('utf-8') 10 11 # 響應返回的是字符串,解析為HTML DOM模式 text = etree.HTML(response) 12 text=etree.HTML(response) 13 # 返回所有段子的結點位置,contains()模糊查詢方法,第一個參數是要匹配的標簽,第二個參數是標簽名部分內容 14 node="//div[contains(@class,'panel panel20')]" 15 node_list=text.xpath(node) 16 # print(node_list) 17 18 for node in node_list: 19 # xpath返回的列表,這個列表就這一個參數,用索引方式取出來,用戶名 20 img = node.xpath("./div[1]/img/@src")[0] 21 title = node.xpath("./div[2]/h2/a/@title")[0] 22 # 取出標簽下的內容,段子內容 23 # content = node.xpath("./div[2]/div")[0].text //遇到有 和<br>后,文本內容沒有取全 24 content = node.xpath("normalize-space(./div[2]/div)") #normalize-space()遇到有 和<br>后,文本內容正常取 25 zan = node.xpath("./div[3]/ul/li[1]/a")[0].text 26 buzan = node.xpath("./div[3]/ul/li[2]/a")[0].text 27 28 items={ 29 "img": img, 30 "title":title, 31 "content":content.replace("\xa0",""), 32 "zan":zan, 33 "buzan":buzan, 34 } 35 36 # print(items) 37 with open('waduanzi.json','a') as f: 38 f.write(json.dumps(items,ensure_ascii=False)+",\n") 39 40 with open('waduanzi.json','r') as f1: 41 print(f1.read())
XPath實例測試
1. 獲取所有的 <li>
標簽
# xpath_li.py from lxml import etree html = etree.parse('hello.html') print type(html) # 顯示etree.parse() 返回類型 result = html.xpath('//li') print result # 打印<li>標簽的元素集合 print len(result) print type(result) print type(result[0])
輸出結果:
<type 'lxml.etree._ElementTree'> [<Element li at 0x1014e0e18>, <Element li at 0x1014e0ef0>, <Element li at 0x1014e0f38>, <Element li at 0x1014e0f80>, <Element li at 0x1014e0fc8>] 5 <type 'list'> <type 'lxml.etree._Element'>
2. 繼續獲取<li>
標簽的所有 class
屬性
# xpath_li.py from lxml import etree html = etree.parse('hello.html') result = html.xpath('//li/@class') print result
運行結果
['item-0', 'item-1', 'item-inactive', 'item-1', 'item-0']
3. 繼續獲取<li>
標簽下hre
為 link1.html
的 <a>
標簽
# xpath_li.py from lxml import etree html = etree.parse('hello.html') result = html.xpath('//li/a[@href="link1.html"]') print result
運行結果
[<Element a at 0x10ffaae18>]
4. 獲取<li>
標簽下的所有 <span>
標簽
# xpath_li.py from lxml import etree html = etree.parse('hello.html') #result = html.xpath('//li/span') #注意這么寫是不對的: #因為 / 是用來獲取子元素的,而 <span> 並不是 <li> 的子元素,所以,要用雙斜杠 result = html.xpath('//li//span') print result
運行結果
[<Element span at 0x10d698e18>]
5. 獲取 <li>
標簽下的<a>
標簽里的所有 class
# xpath_li.py from lxml import etree html = etree.parse('hello.html') result = html.xpath('//li/a//@class') print result
運行結果
['blod']
6. 獲取最后一個 <li>
的 <a>
的 href
# xpath_li.py from lxml import etree html = etree.parse('hello.html') result = html.xpath('//li[last()]/a/@href') # 謂語 [last()] 可以找到最后一個元素 print result
運行結果
['link5.html']
7. 獲取倒數第二個元素的內容
# xpath_li.py from lxml import etree html = etree.parse('hello.html') result = html.xpath('//li[last()-1]/a') # text 方法可以獲取元素內容 print result[0].text
運行結果
fourth item
8. 獲取 class
值為 bold
的標簽名
# xpath_li.py from lxml import etree html = etree.parse('hello.html') result = html.xpath('//*[@class="bold"]') # tag方法可以獲取標簽名 print result[0].tag
運行結果
span