xpath轴

child::book    选取所有属于当前节点的子元素的 book 节点。
attribute::lang    选取当前节点的 lang 属性。
child::*    选取当前节点的所有子元素。
attribute::*    选取当前节点的所有属性。
child::text()    选取当前节点的所有文本子节点。
child::node()    选取当前节点的所有子节点。
descendant::book    选取当前节点的所有 book 后代。
ancestor::book    选择当前节点的所有 book 先辈。
ancestor-or-self::book    选取当前节点的所有 book 先辈以及当前节点(如果此节点是 book 节点)
child::*/child::price    选取当前节点的所有 price 孙节点。
from lxml import etree

html = '''
<!DOCTYPE html>
<html lang="en">
<head>
    <!--网页头部信息-->
    <title>网页名</title>
</head>
<body>
    <!--下面是网页正文-->
    <div class="two" name='test' style="color:red">id-text</div>
    <div class="one two">class-text</div>
    <div class="one">class-span</div>
    <div class="three">three</div>
</body>
</html>
'''

html =etree.HTML(html)

content1 = html.xpath("//div/ancestor::*") #选取div的所有父和祖父节点
content1 = html.xpath("//div[@class='two']/attribute::*") #选取节点的所有属性
content1 = html.xpath("//div[@class='two']/attribute::style") #选取节点的style属性
content1 = html.xpath(".//body/child::div") #选取所有子节点

print(content1)

  

原文地址:https://www.cnblogs.com/php-linux/p/12462026.html