html = """ <html> <head> <meta charset="UTF-8"> </head> <body> <div class='main-content'> <h1 id="title">Test Page</h1> <p id=“first” class="text-first">This is paragraph1</p> <div> <p>测试语句1</p> </div> </div> <div> <p class="text-second">This is paragraph2</p> <p class="text-third">This is paragraph3</p> <div> <p>测试语句2</p> </div> </div> </body> </html> """
page = etree.HTML(html)
通过节点和 ‘/‘ 结合,我们可以简单地查找某一个节点:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# 在 div 节点下寻找所有 p 子节点 test1 = page.xpath('/html/body/div/p') print(test1[0].text) # This is paragraph1 print(test1[1].text) # This is paragraph2 print(test1[2].text) # This is paragraph3
# 在 div 节点下寻找所有 p 节点 test2 = page.xpath('/html/body/div//p') for item in test2: print(item.text) # This is paragraph1 # 测试语句1 # This is paragraph2 # This is paragraph3 # 测试语句2
若想查询具体位置的节点,可以为节点添加下标,不过下标应从 1 开始,如:
1 2 3 4
# 查询第一个 div 内的 p 子节点 test3 = page.xpath('/html/body/div[1]/p') # 查询第一个 div 内所有节点 test4 = page.xpath('/html/body/div[1]//*')
通过 @ 符号选择属性更具体的选择节点:
1 2 3 4 5 6
# 在根节点中选择所有 id="title” 的节点 test5 = page.xpath('//*[@id="title"]') # Test Page # 在根节点中选择所有 class="text-second" 的 p 节点 test6 = page.xpath('//p[@class="text-second"]') # This is paragraph2 # 多属性筛选 test7 = page.xpath('//p[@class="text-first" and @id="first"]')