案例: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

相关推荐
HarmonLTS10 分钟前
Python Socket网络通信详解
服务器·python·网络安全
willingli11 分钟前
c语言经典100题 61-70题
c语言·开发语言·算法
我是小疯子6616 分钟前
深入解析C++右值引用与移动语义
java·开发语言·算法
Ethan Wilson18 分钟前
VS2019 C++20 模块相关 C1001: 内部编译器错误
开发语言·c++·c++20
郝学胜-神的一滴21 分钟前
Python数据封装与私有属性:保护你的数据安全
linux·服务器·开发语言·python·程序人生
悟能不能悟23 分钟前
Elastic Stack 中两种主要查询语言 KQL (Kibana Query Language) 和 Lucene 的详细对比和解释。
java·开发语言
智航GIS28 分钟前
11.7 使用Pandas 模块中describe()、groupby()进行简单分析
python·pandas
Pyeako33 分钟前
机器学习--矿物数据清洗(六种填充方法)
人工智能·python·随机森林·机器学习·pycharm·线性回归·数据清洗
赛恩斯1 小时前
kotlin 为什么可以在没有kotlin 环境的安卓系统上运行的
android·开发语言·kotlin
steem_ding1 小时前
net.core 调优指南
开发语言·php