Python爬蟲必備之XPath解析庫
XPath 是一門在 XML 文檔中查找信息的語言。XPath 可用來在 XML 文檔中對元素和屬性進行遍歷。XPath 是 W3C XSLT 標準的主要元素,并且 XQuery 和 XPointer 都構建于 XPath 表達之上。
Xpath解析庫介紹:數據解析的過程中使用過正則表達式, 但正則表達式想要進準匹配難度較高, 一旦正則表達式書寫錯誤, 匹配的數據也會出錯。
網頁由三部分組成: HTML, Css, JavaScript, HTML頁面標簽存在層級關系, 即DOM樹, 在獲取目標數據時可以根據網頁層次關系定位標簽, 在獲取標簽的文本或屬性。
二、安裝pip install lxml三、節點3.1 選取節點
XPath 使用路徑表達式在 XML 文檔中選取節點。節點是通過沿著路徑或者 step 來選取的。 下面列出了最有用的路徑表達式:
表達式 描述 nodename 選取此節點的所有子節點。 / 從根節點選取。 // 從匹配選擇的當前節點選擇文檔中的節點,而不考慮它們的位置。 … 選取當前節點的父節點。 . 選取當前節點。 @ 選取屬性。 3.2 選取未知節點XPath 通配符可用來選取未知的 XML 元素。
通配符 描述 * 匹配任何元素節點。 @* 匹配任何屬性節點。 node() 匹配任何類型的節點。在下面的表格中,我們列出了一些路徑表達式,以及這些表達式的結果:
路徑表達式 結果 /bookstore/* 選取 bookstore 元素的所有子元素。 //* 選取文檔中的所有元素。 //title[@*] 選取所有帶有屬性的 title 元素。 3.3 節點關系父(Parent)
每個元素以及屬性都有一個父。在下面的例子中,book 元素是 title、author、year 以及 price 元素的父:
<book> <title>Harry Potter</title> <author>J K. Rowling</author> <year>2005</year> <price>29.99</price></book>
子(Children)
元素節點可有零個、一個或多個子。在下面的例子中,title、author、year 以及 price 元素都是 book 元素的子:
<book> <title>Harry Potter</title> <author>J K. Rowling</author> <year>2005</year> <price>29.99</price></book>
同胞(Sibling)
擁有相同的父的節點在下面的例子中,title、author、year 以及 price 元素都是同胞:
<book> <title>Harry Potter</title> <author>J K. Rowling</author> <year>2005</year> <price>29.99</price></book>
先輩(Ancestor)
某節點的父、父的父,等等。在下面的例子中,title 元素的先輩是 book 元素和 bookstore 元素:
<bookstore><book> <title>Harry Potter</title> <author>J K. Rowling</author> <year>2005</year> <price>29.99</price></book></bookstore>
后代(Descendant)
某個節點的子,子的子,等等。在下面的例子中,bookstore 的后代是 book、title、author、year 以及 price 元素:
<bookstore><book> <title>Harry Potter</title> <author>J K. Rowling</author> <year>2005</year> <price>29.99</price></book></bookstore>四、XPath實例
爬取糗事百科
import requests# 導包from lxml import etreeimport osbase_url = ’https://www.qiushibaike.com/video/’headers = { ’User-Agent’: ’Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36’}res = requests.get(url=base_url, headers=headers)html = res.content.decode(’utf-8’)# xpath解析tree = etree.HTML(html)# 標題content = tree.xpath(’//*/a/div[@class='content']/span/text()’)# 視頻video_list = tree.xpath(’//*/video[@controls='controls']/source/@src’)index = 0for i in video_list: # 獲取視頻二進制流 video_content = requests.get(url= ’https:’ + i,headers=headers).content # 標題 title_1 = content[0].strip(’n’) # 將視頻二進制寫入文件 with open(f’Video/{title_1}.mp4’,’wb’) as f:f.write(video_content) index += 1
到此這篇關于Python爬蟲必備之XPath解析庫的文章就介紹到這了,更多相關XPath解析庫內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: