xpath 學習

安裝xpath

pip install lxml

Xpath 常用規則

xpath 學習


話不多說,看代碼

from lxml import etree

doc = '''
<html>
 <head>
  <base href='http://example.com/' />
  <title>Example website</title>
 </head>
 <body>
  <div id='images'>
   <a href='image1.html'>Name: My image 1 <br /><img src='image1_thumb.jpg' /></a>
   <a href='image2.html'>Name: My image 2 <br /><img src='image2_thumb.jpg' /></a>
   <a href='image3.html'>Name: My image 3 <br /><img src='image3_thumb.jpg' /></a>
   <a href='image4.html'>Name: My image 4 <br /><img src='image4_thumb.jpg' /></a>
   <a href='image5.html' class='li li-item' name='items'>Name: My image 5 <br /><img src='image5_thumb.jpg' /></a>
   <a href='image6.html' name='items'><span><h5>test</h5></span>Name: My image 6 <br /><img src='image6_thumb.jpg' /></a>
  </div>
 </body>
</html>
'''

html = etree.HTML(doc)

# /一個斜槓表示子級標籤
# //兩個斜槓表示子孫標籤

# 1 所有節點
a = html.xpath('//*')  # 返回一個列表
for i in a:
    print(i.text)  # text 表示獲取該節點的文本信息

# 2 指定節點(結果爲列表)
a = html.xpath('//head')

# 3 子節點,子孫節點
a=html.xpath('//div/a')
a=html.xpath('//body/a') #無數據
a=html.xpath('//body//a')

# 4 父節點
a=html.xpath('//body//a[@href="image1.html"]/..')
a=html.xpath('//body//a[1]/..')
# 也可以這樣
a=html.xpath('//body//a[1]/parent::*')

# 5 屬性匹配
a=html.xpath('//body//a[@href="image1.html"]')

# 6 文本獲取
a=html.xpath('//body//a[@href="image1.html"]/text()')

# 7 屬性獲取
a=html.xpath('//body//a/@href')
# # 注意從1 開始取(不是從0)
a=html.xpath('//body//a[1]/@href')

# 8 屬性多值匹配
#  a 標籤有多個class類,直接匹配就不可以了,需要用contains
a=html.xpath('//body//a[@class="li"]')
a=html.xpath('//body//a[contains(@class,"li")]')
a=html.xpath('//body//a[contains(@class,"li")]/text()')

# 9 多屬性匹配
a=html.xpath('//body//a[contains(@class,"li") or @name="items"]')
a=html.xpath('//body//a[contains(@class,"li") and @name="items"]/text()')
a=html.xpath('//body//a[contains(@class,"li")]/text()')

# 10 按序選擇
a=html.xpath('//a[2]/text()')
a=html.xpath('//a[2]/@href')

# 取最後一個
a=html.xpath('//a[last()]/@href')

# 位置小於3的
 a=html.xpath('//a[position()<3]/@href')

# 倒數第二個
a=html.xpath('//a[last()-2]/@href')

# 11 節點軸選擇
# ancestor:祖先節點
# 使用了* 獲取所有祖先節點
a=html.xpath('//a/ancestor::*')

# # 獲取祖先節點中的div
a=html.xpath('//a/ancestor::div')

# attribute:屬性值
a=html.xpath('//a[1]/attribute::*')

# child:直接子節點
a=html.xpath('//a[1]/child::*')

# descendant:所有子孫節點
a=html.xpath('//a[6]/descendant::*')

# following:當前節點之後所有節點
a=html.xpath('//a[1]/following::*')
a=html.xpath('//a[1]/following::*[1]/@href')

# following-sibling:當前節點之後同級節點
a=html.xpath('//a[1]/following-sibling::*')
a=html.xpath('//a[1]/following-sibling::a')
a=html.xpath('//a[1]/following-sibling::*[2]')
a=html.xpath('//a[1]/following-sibling::*[2]/@href')
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章