python lxml怎么选取html注释_python HTML解析之 - lxml

lxml是处理XML和HTML的python语言,解析的时候,自动处理各种编码问题。而且它天生支持 XPath 1.0、XSLT 1.0、定制元素类。

安装:

pip install lxml

lxml用法

HTML 实例

Study/title>

webpage

source link

HTML

Python

C++

Java

(1)HTML读取

test, test.html指上述实例

直接读取内容

from lxml import etree

html = etree.HTML(test)

直接读取文件

from lxml import etree

html = etree.parse(test.html)

(2)获取标签

获取a的所有标签, 这种html内容有多种写法,可以 直接得到了4个元素。

//a:获取html下的所有 a 标签

/html/body/a:沿着节点顺序找 a 标签

/descendant::a:当前节点后代里面找 a 标签

a_tags = html.xpath('//a')

In [12]: print a_tags

[, , , ]

a_tags_2 = html.xpath('/html/body/a')

In [14]: print a_tags

[, , , ]

a_tags_3 = html.xpath('/descendant::a')

In [16]: print a_tags_3

[, , , ]

(3)获取标签属性, 文本

按照(2)中的方法,再加上/@href,可以直接得到属性值。

a_attribute_2 = html.xpath('/html/body/a/@href')

In [21]: print a_attribute_2

['http://www.runoob.com/html/html-tutorial.html', 'http://www.runoob.com/python/python-tutorial.html', 'http://www.runoob.com/cplusplus/cpp-tutorial.html', 'http://www.runoob.com/java/java-tutorial.html']

a_text_2 = html.xpath('/html/body/a/text()')

In [31]: print a_text_2

['HTML', 'Python', 'C++', 'Java']

或者得到(2)中的结果,一一轮询。

for tag in a_tags_2:

print tag.attrib, tag.text

{'href': 'http://www.runoob.com/html/html-tutorial.html', 'target': '_blank'} HTML

{'href': 'http://www.runoob.com/python/python-tutorial.html', 'target': '_blank'} Python

{'href': 'http://www.runoob.com/cplusplus/cpp-tutorial.html', 'target': '_blank'} C++

{'href': 'http://www.runoob.com/java/java-tutorial.html', 'target': '_blank'} Java

(4)筛选标签

按照属性

python_tag = html.xpath('/html/body/a[@href="http://www.runoob.com/python/python-tutorial.html"]')

In [42]: print python_tag[0].attrib

{'href': 'http://www.runoob.com/python/python-tutorial.html', 'target': '_blank'}

In [43]: print python_tag[0].text

Python

按照文本

python_tag = html.xpath('/html/body/a[text()="Python"]')

In [47]: print python_tag[0].attrib

{'href': 'http://www.runoob.com/python/python-tutorial.html', 'target': '_blank'}

In [48]: print python_tag[0].text

Python

按照位置

python_tag = html.xpath('/html/body/a[position()=2]')

# python_tag = html.xpath('/html/body/a[2]')

In [52]: print python_tag[0].attrib

{'href': 'http://www.runoob.com/python/python-tutorial.html', 'target': '_blank'}

In [53]: print python_tag[0].text

Python

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值