from
lxml
import
etree
#https://mirrors.aliyun.com/pypi/simple/ python仓库
wb_data
=
"""
<div>
<ul>
<li class="item-0"><a href="link1.html">first item</a></li>
<li class="item-1"><a href="link2.html">second item</a></li>
<li class="item-inactive"><a href="link3.html">third item</a></li>
<li class="item-3"><a href="link4.html">fourth item</a></li>
<li class="item-4"><a href="link5.html">fifth item</a></li>
</ul>
</div>
"""
#将变量读取为HTML对象,自动添加<html><body>... ...</body></html>
html
=
etree.HTML(wb_data)
#解析数据 /是根节点
data
=
html.xpath(
'/html'
)
/
/
子孙节点
data2
=
html.xpath(
'//li'
) li标签可以在任意节点
获取a标签里的内容
1
data3
=
html.xpath(
'/html/body/div/ul/li/a/text()'
)
获取
class
属性的属性值
data5
=
html.xpath(
'/html/body/div/ul/li/@class'
)
for
i
in
data
print
(i)
获取a标签里的内容
2
data4
=
html.xpath(
'/html/body/div/ul/li/a'
)
获取所有href属性中带有link2.html属性值的标签的内容
data8
=
html.xpath(
'//ul/li/a[@href="link2.html"'
)
for
i
in
data4:
print
(i.text)
获取a标签的href属性的属性值
data6
=
html.xpath(
'/html/body/div/ul/li/a'
)
for
i
in
data6:
a
=
i.xpath(
'./@href'
)
print
(a)
获取第一个和最后一个li标签的地址
#这里data7是一个list 电脑不知道ul有几个,就将ul标签当做多个ul处理,多个ul就是列表
data7
=
html.xpath(
'/html/body/div/ul'
)
for
i
in
data7:
li_1
=
i.xpath(
'./li[1]'
)
print
(li_1)
li_last
=
i.xpath(.
/
li[last()]')
print
(li_last)
*
位置节点,匹配所有li标签下的有text的标签的内容
data
=
html.xpath(
'//ul/li/*'
)
for
i
in
data:
if
hasattr
(i,
'text'
):
print
(i.text)
else
:
print
(i)
#自定义解释器,解析html文件
parser
=
etree.HTMLParser(encoding
=
'utf-8'
) 默认解析xml文档
html_file
=
etree.parse(
'aliyun.html'
,parser
=
parser)
匹配任意节点,带有text的内容
data
=
html_file.xpath(
'//*'
)
for
i
in
data:
if
hasattr
(i,
'text'
):
print
(i.text)
获取a链接href的属性值为link2.html的内容"
html_file
=
etree.parse(
'hh.html'
,parser
=
parser)
data
=
html_file.xpath(
'//li/a[@href="link2.html"]/text()'
)
print
(data)
获取a链接href的属性的值
data
=
html_file.xpath(
'//li/a/@href'
)
print
(data)
谓语
获取最后一个a链接的内容
data
=
html_file.xpath(
'//li[last()]/a/text()'
)
print
(data)