xpath兄弟结点语法

代码

from lxml import etree


html = """
<div>
    <hello> 我是hello标签 </hello>
    <a id="1" href="www.baidu.com"> 我是第1个a标签 </a>
    <p> 我是p标签0 </p>
    <a id="2" href="www.baidu.com"> 我是第2个a标签 </a>
    <demo> demo </demo>
    <a id="3" href="www.baidu.com"> 我是第3个a标签 </a>
    <a id="4" href="www.baidu.com"> 我是第4个a标签 </a>
    <p> 我是p标签1 </p>
    <p> 我是p标签2 </p>
    <python>  我是Python标签  </python>
    <a id="5" href="www.baidu.com">我是第5个a标签</a>
</div>
"""

x_html = etree.HTML(html)

# 下方兄弟标签演示
# 获取demo标签下方的(第1个p标签);
p1 = x_html.xpath('//demo/following-sibling::p[1]//text()')
print(p1)
# 获取demo标签下方的(第2个p标签);
p2 = x_html.xpath('//demo/following-sibling::p[2]//text()')
print(p2)
# 获取demo标签下方的(第4个标签), *表示不指定什么标签,按照上到下顺序的第4个标签即可
python = x_html.xpath('//demo/following-sibling::*[5]//text()')
print(python)
print()

# 上方兄弟标签
# 获取demo标签上方的(第1个a标签)
a2 = x_html.xpath('//demo/preceding-sibling::a[1]//text()')
print(a2)
# 获取demo标签上方的(第2个a标签)
a1 = x_html.xpath('//demo/preceding-sibling::a[2]//text()')
print(a1)
# 获取demo标签上方的(第4个标签), *表示不指定什么标签,按照下到上顺序的第4个标签即可
hello = x_html.xpath('//demo/preceding-sibling::*[4]//text()')
print(hello)

输出结果

在这里插入图片描述

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值