Python爬虫学习(三):parsel解析html

parse中可以使用css及xpath对html和xml进行解析,其中主要用到的方法如上图所示,并支持使用 XPath 和 CSS Selector 对内容进行提取和修改,同时它还融合了正则表达式提取的功能。方法使用代码示例如下,关于xpath相关方法的使用可以参照:Python爬虫学习(二):xpath解析html-CSDN博客

python 复制代码
from parsel import Selector
​
​
def parseDemo():
    html = '''
           <div>
               <ul>
                    <li class="item-0"><a href="link1.html">first item</a></li>
                    <li class="item-1"><a href="link2.html">second item</a></li>
                    <li class="item-inactive"><a href="link3.html">third item</a></li>
                    <li class="item-1"><a href="link4.html">fourth item</a></li>
                    <li class="item-0"><a href="link5.html">fifth item</a>
                </ul>
            </div>
       '''
    # 创建一个selector对象
    res = Selector(text=html, encoding='utf-8')
    # 通过css方法获取class为item-0的元素
    cssRes = res.css('.item-0')
    print(cssRes)
    # 返回的类型为<class 'parsel.selector.SelectorList'>
    print(type(cssRes))
    xpathRes = res.xpath('//li/a')
    print(xpathRes)
    # 返回的类型同为<class 'parsel.selector.SelectorList'>
    print(type(xpathRes))
    # 基于上述返回类型可以使用for循环进行相关逻辑操作
    for cssres in cssRes:
        # getall方法是获取所有
        print(cssres.xpath('.//text()').getall())
    # get方法是获取第一个
    result1 = res.css('.item-0 a::attr(href)').get()
    print(result1)
    result2 = res.xpath('//li[contains(@class, "item-0") and contains(@class, "active")]/a/@href').get()
    print(result2)
​
​
if __name__ == "__main__":
    parseDemo()
相关推荐
Lyn_Li2 小时前
Kaggle Top 5 | 198只股票、200条数据的金融预测——BattleFin高分方案从零复现
python·kaggle·比赛复盘·金融预测
小九九的爸爸6 小时前
前端想要入门Agent开发,要具备哪些Python基础?
python·agent·ai编程
阿耶同学7 小时前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构
python·程序员
花酒锄作田1 天前
Pydantic校验配置文件
python
hboot1 天前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi1 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi1 天前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽1 天前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
用户8358086187912 天前
基于 Self-RAG 与列表级重排序的进阶 RAG 系统设计与实现
python
Warson_L2 天前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python