爬蟲必會的xpath

2021-09-16 12:21:43 字數 1369 閱讀 9406

from lxml import etree

#用來獲取解析後的資料

html = etree.html(text)#用來解析文字

html = etree.parse(「index2.html」)#用來解析html文件

#1獲取文件中的所有標籤

books = html.xpath("//book")

#2第乙個book

first_book = book[0]

#3 獲取第一本book中的href標籤

href = first_book.xpath(".//@href")

print(href,111111111)

#4獲取當前節點的父節點的所有book標籤的href屬性

book_hrefs = first_book.xpath("…/book/@href")

print(book_hrefs)

#5獲取**大於40的book書名

book_name = html.xpath("//book[price>40]/title/text()")

print(book_name)

#6獲取**等於99.5的書名

book_name = html.xpath("//book[price=99.95]/title/text()")

print(book_name)

#7獲取book標籤下面的title和price標籤

title_price = html.xpath("//book/title | //book/price")

print(title_price)

#8.獲取bookstore下面的最前面的兩個標籤,並獲取它的書名

book_name2 = html.xpath("/bookestore/book[positon()❤️]/title/text()")

print(book_name2)

#9獲取所有節點屬性

nodes = html.xpath("//@*")

print(nodes)

#10獲取所有帶有屬性的title標籤,並獲取書名

book_name3 = html.xpath("//title[@*]")

print(book_name3)

#11獲取屬性href為的book標籤,獲取他的兄弟標籤下的title書名

book_name4 = html.xpath("//book[@href=『』]/following-sibling::book/title/text()")

print(book_name4)

#12獲取所有的書名,child 是zi標籤

book_name6 = html.xpath("//book/child::title/text()")

xpath 爬蟲利器

用xpath的爬取網頁內容的初步了解 xpath提取文字內容 text 提取屬性內容 coding utf 8 author zjp from lxml import etree import requests url response1 requests.get url 獲取網頁響應 select...

爬蟲 xpath 匹配

從根標籤開始 必須具有嚴格的父子關係 從當前標籤 後續節點含有即可選出 import lxml.html test data 111111 29.99 222222 39.95 33333 40 123 萬用字元,選擇所有 div book 1 title 選擇div下第乙個book標籤的title...

爬蟲入門 XPATH

識別符號 作用節點名 獲取節點的所有子節點 獲取屬性 從根節點獲取 從匹配選擇的當前節點擊擇文件中的節點,而不考慮它們的位置 獲取當前節點 獲取當前節點的父節點 可以通過組合使用縮小搜尋的範圍 以下面的為例子 元素 標籤 strong div標籤中的 class cover wp 標籤中間的內容 8...