1、安装
pip insatll lxml
from lxml import etree
2、xpath解析文件
<ul>
<li id="12" clazz = 15>北京</li>
<li>上海</li>
<li>武汉</li>
</ul>
3、解析本地文件
tree = etree.parse('demo10pachong.html')
print(tree)
4、xpath基本语法
(1)路径查询(查看html文件中标签,层层深入)
//子孙节点
/子节
li_list = tree.xpath('//body/ul/li')
print(li_list)
print(len(li_list))
(2)谓词查询,属性查询,模糊查询,内容查询
li_list2 =tree.xpath('//ul/li[@id]/text()')
li_list2 =tree.xpath('//ul/li[@id="12"]/text()')
li_list2 =tree.xpath('//ul/li[@id="12"]/@class')
print(li_list2)
li_list3 = tree.xpath('//ul/li[contains(@id,"l")]/text()')
print(li_list3)
d
li_list4 = tree.xpath('//ul/li[starts-with(@id,"l")]/text()')
print(li_list4)
5、解析
from lxml import etree
import urllib.request
from fake_headers import Headers
url = "https://www.baidu.com/"
header =Headers(
browser='chrome',
os = 'win',
headers=True
)
request = urllib.request.Request(url=url,headers=header.generate())
res = urllib.request.urlopen(request)
content = res.read().decode('utf-8')
print(content)
tree = etree.HTML(content)
result = tree.xpath('//input[@id="su"]/@value')[0]
print(result)
|