python中xpath常用方法 小结

这是一个test.html文件内容

<!-- hello.html -->
<div>
<ul>
<li class="item-0" text="1"><a href="link1.html">first item</a></li>
<li class="item-1" text="2"><a href="link2.html">second item</a></li>
<li class="item-inactive" text="3"><a href="link3.html"><span class="bold">third item</span></a></li>
<li class="item-1" text="2"><a href="link4.html">fourth item</a></li>
<li class="item-0" text="1"><a href="link5.html">fifth item</a></li>
</ul>
</div>


以下是xpath使用方法

#coding:utf-8
import lxml
import lxml.etree

html=lxml.etree.parse("test.html")
print type(html)
res=html.xpath("//li")
print res
print len(res)#列表长度
print type(res) #元素列表
print type(res[0]) #树的元素

res1=html.xpath("//li/@class") #同级目录
print res1

res2=html.xpath("//li/@text")
print res2

res3=html.xpath("//li/a")#取出下一级
print res3

res4=html.xpath("//li/a/@href") #取出下一级的某个通有元素
print res4

res5=html.xpath("//li/a[@href=\"link3.html\"]") #取出下一级的某个通有元素
print res5

res6=html.xpath("//li//span") #取出下一级的某个通有元素
print res6

res6=html.xpath("//li//span/@class") #取出下一级的某个通有元素de class属性
print res6

res7=html.xpath("//li/a//@class") #取出下一级的某个通有元素de class属性
print res7

#res8=html.xpath("//li[1]") #第一个
res8=html.xpath("//li[last()]") #最后一个
print res8

res9=html.xpath("//li[last()]/a/@href") #最后一个li下面的a中的href
print res9

res9=html.xpath("//li[last()-1]/a/@href") #最后一个li下面的a中的href
print res9

res10=html.xpath("//*[@class=\"bold\"]") #最后一个li下面的a中的href
print res10

res11=html.xpath("//*[@text=\"3\"]") #最后一个li下面的a中的href
print res11

res11=html.xpath("//*[@text=\"3\"]/@class") #最后一个li下面的a中的href
print res


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值