目录

一、前提

二、html内容转换

三、元素的获取

1.获取html所有标签节点

2.查找指定标签的所有节点

3.查找指定属性名称的节点

4.查找指定标签名称的内容

5.查找指定标签的父节点

6.查找指定标签的所有属性的值

7.查找指定标签和属性的节点

8.查找指定标签,属性和属性值的节点

9.查找指定标签,有多个属性的节点

10.查找指定标签,单个属性有多个值的节点



一、前提

已获取到html文件,已安装lxml库,元素的获取方式主要通过xpath,并且对xml文件也适用

二、html内容转换

将html的内容转换成字符串

from lxml import etree
#将html文档转换成字符串对象
with open(r"C:\Users\Administrator\Desktop\test_python\html\regression2.html",encoding="utf-8") as f:
    content = " ".join([r.rstrip() for r in f])

三、元素的获取

1.获取html所有标签节点

#查找所有html的所有标签节点,返回结果为列表
html=etree.HTML(content,etree.HTMLParser())
result=html.xpath("//*")
print("result:",result)

2.查找指定标签的所有节点

#查找所有标签名为name的所有节点
html=etree.HTML(content,etree.HTMLParser())
result=html.xpath("//name")
print("result:",result)

3.查找指定属性名称的节点

#查找具有属性值sex的节点
html=etree.HTML(content,etree.HTMLParser())
result=html.xpath("//@sex//..")
print("result:",result)

4.查找指定标签名称的内容

#查找所有标签名为name的内容
html=etree.HTML(content,etree.HTMLParser())
result=html.xpath("//name//text()")
print("result:",result)

5.查找指定标签的父节点

#查找所有标签为updated的父节点,返回结果为列表
html=etree.HTML(content,etree.HTMLParser())
result=html.xpath("//updated/..")
print("table:",result)

6.查找指定标签的所有属性的值

 如果有多个标签名称都为name,则统计他们所有的属性值

#查找所有标签名为name的所有属性值
html=etree.HTML(content,etree.HTMLParser())
result=html.xpath("//name//@*")
print("result:",result)

7.查找指定标签和属性的节点

#查找所有标签名为name,且具有属性sex的所有节点
html=etree.HTML(content,etree.HTMLParser())
result=html.xpath("//name[@sex]")
print("result:",result)

8.查找指定标签,属性和属性值的节点

#查找所有标签名为name,属性sex的值为male的所有节点
html=etree.HTML(content,etree.HTMLParser())
result=html.xpath("//name[@sex='male']")
print("result:",result)

9.查找指定标签,有多个属性的节点

#查找标签名为name,同时具有属性sex="male",age="30"
html=etree.HTML(content,etree.HTMLParser())
result=html.xpath(" //name[contains(@sex,'male') and @age='30']")
print("result:",result)

10.查找指定标签,单个属性有多个值的节点

#查找标签名为name,属性age有多个值,其中有一个值为40
html=etree.HTML(content,etree.HTMLParser())
result=html.xpath('//name[contains(@age,"40")]')
print("result:",result)

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐