案例:xpath实例+功能

素材:test.html 代码如下:

html 复制代码
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>Title</title>
    </head>
    <body>
        <span>我爱你</span>
        <ul>
            <li><a href="http://www.baidu.com">百度</a></li>
            <li><a href="http://www.google.com">谷歌</a></li>
            <li><a href="http://www.sogou.com">搜狗</a></li>
        </ul>
        <ol>
            <li><a href="feiji">飞机</a></li>
            <li><a href="dapao">大炮</a></li>
            <li><a href="huoche">火车</a></li>
        </ol>
        <div class="job">李嘉诚</div>
        <div class="common">胡辣汤</div>
    </body>
</html>

爬虫代码:常用

python 复制代码
from lxml import etree
# from lxml import html
# etree = html.etree
# # 需要加载准备解析的数据
f= open('test.html',mode='r',encoding='utf-8')
pageSource=f.read()
# print(pageSource)
# 加载数据,返回element对象
et=etree.HTML(pageSource)
# print(et)
# xpath语法
# result = et.xpath('/html') #/html表示根节点
# result = et.xpath('/html/body') #表达式中的/表示一层html节点
# result = et.xpath('/html/body/span/text()') #text()表示提取标签中的文本信息
# result = et.xpath('/html/body/*/li/a/text()') # * 表示任意的,通配符,
# result = et.xpath('/html/body/*/li/a/@href') # @ 表示属性
# result = et.xpath('//li/a/@href') # // 表示任意位置
# result = et.xpath('//div[@class="job"]/text()') # [@xx='xx'] 表示属性上的限定
# print(result)

# 带循环的
result = et.xpath("/html/body/ul/li")
for item in result:
    href = item.xpath("./a/@href")[0] # ./ 表示当前这个元素
    text = item.xpath("./a/text()")[0]
    print(text,href)

运行结果如下:

百度 http://www.baidu.com

谷歌 http://www.google.com

搜狗 http://www.sogou.com

相关推荐
ponponon35 分钟前
时代的眼泪,nameko 和 eventlet 停止维护后的项目自救,升级和替代之路
python
Flittly36 分钟前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(5)Skills (技能加载)
python·agent
敏编程1 小时前
一天一个Python库:pyarrow - 大规模数据处理的利器
python
Flittly3 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(4)Subagents (子智能体)
python·agent
明月_清风9 小时前
Python 装饰器前传:如果不懂“闭包”,你只是在复刻代码
后端·python
明月_清风9 小时前
打破“死亡环联”:深挖 Python 分代回收与垃圾回收(GC)机制
后端·python
ZhengEnCi1 天前
08c. 检索算法与策略-混合检索
后端·python·算法
明月_清风1 天前
Python 内存手术刀:sys.getrefcount 与引用计数的生死时速
后端·python
明月_清风1 天前
Python 消失的内存:为什么 list=[] 是新手最容易踩的“毒苹果”?
后端·python
Flittly2 天前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(3)TodoWrite (待办写入)
python·agent