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()
相关推荐
Yan-英杰29 分钟前
百度搜索和文心智能体接入DeepSeek满血版——AI搜索的新纪元
图像处理·人工智能·python·深度学习·deepseek
weixin_307779131 小时前
Azure上基于OpenAI GPT-4模型验证行政区域数据的设计方案
数据仓库·python·云计算·aws
玩电脑的辣条哥2 小时前
Python如何播放本地音乐并在web页面播放
开发语言·前端·python
CSDN_PBB3 小时前
[STM32 - 野火] - - - 固件库学习笔记 - - - 十五.设置FLASH的读写保护及解除
笔记·stm32·学习
多想和从前一样5 小时前
Django 创建表时 “__str__ ”方法的使用
后端·python·django
小喵要摸鱼7 小时前
【Pytorch 库】自定义数据集相关的类
pytorch·python
bdawn7 小时前
深度集成DeepSeek大模型:WebSocket流式聊天实现
python·websocket·openai·api·实时聊天·deepseek大模型·流式输出
Jackson@ML7 小时前
Python数据可视化简介
开发语言·python·数据可视化
mosquito_lover17 小时前
怎么把pyqt界面做的像web一样漂亮
前端·python·pyqt
鸡啄米的时光机7 小时前
vscode的一些实用操作
vscode·学习