pip install lxml -i https://mirrors.tuna.tsinghua.edu.cn/
from lxml import etree
tree = etree.parse('xx.html')
tree = etree.HTML(response.read().decode('utf-8'))
tree.xpath('xpath路径')
先写一个本地的HTML文件
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>Titletitle>
head>
<body>
<ul>
<li id="l1" class="c1">北京li>
<li id="l2">上海li>
<li id="c3">天津li>
<li id="c4">重庆li>
ul>
body>
html>
# 查找ul下面的li
li_list = tree.xpath('//ul/li')
print(li_list)
li_list = tree.xpath('//ul/li/text()')
print(li_list)
# 查找所有有id的属性的li标签
# text()获取标签中的内容
li_list1 = tree.xpath('//ul/li[@id]/text()')
print(li_list1)
# 找到id为l1的li标签 注意引号问题
li_list2 = tree.xpath('//ul/li[@id="l1"]/text()')
print(li_list2)
# 查找到id为l1的li标签的class的属性值
li = tree.xpath('//ul/li[@id="l1"]/@class/text()')
print(li)
# 查询id中带l的li标签
li_list3 = tree.xpath('//ul/li[contains(@id, "l")]/text()')
print(li_list3)
# 查询id的值以c开头的li标签
li_list4 = tree.xpath('//ul/li[starts-with(@id, "c")]/text()')
print(li_list4)
# 查询id为l1和class为c1的数据
li_list5 = tree.xpath('//ul/li[@id="l1" and @class="c1"]/text()')
print(li_list5)
# 查询id为l1或者为l2的数据 只能通过标签操作,而不允许属性操作
li_list6 = tree.xpath('//ul/li[@id="l1"]/text() | //ul/li[@id="l2"]/text()')
print(li_list6)