import requests
from lxml import etree
req=requsets.get(url)
req.encoding='utf-8'
html=req.text
# html 是获取到网页文档
html_x=etree.HTML(html)
res=html_x.xpath("xpath解析式")
# 具体 res 的数据类型 踩坑
# type of res is list res的类型是列表
# 获取兄弟元素
/following-sibling::text() # get text of the next sibling
#eg:获取标签div,class为fly-layui的下一个元素的文本
xpath_a = "//div[@class='flu-layui/following-sibling::text()']"
res=html_x.xpath(xpath_a) # 返回列表,节点内的所有文本
# 获取节点的属性,获取id为test-layer的img里面的src
xpath_b="//img[@id='test-layer']/@src"
img_res=html_x.xpath(xpath_B) #返回列表,元素中为src的属性值,其他属性依次类推,区别于文本text(),text不需要加@,属性则不需要加括号*斜体样式*
python3 [XPATH]常用笔记
最新推荐文章于 2024-03-29 20:52:25 发布