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()
相关推荐
databook12 小时前
Manim实现闪光轨迹特效
后端·python·动效
Juchecar13 小时前
解惑:NumPy 中 ndarray.ndim 到底是什么?
python
用户83562907805114 小时前
Python 删除 Excel 工作表中的空白行列
后端·python
Json_14 小时前
使用python-fastApi框架开发一个学校宿舍管理系统-前后端分离项目
后端·python·fastapi
子竹聆风15 小时前
Feapder框架UpdateItem使用技巧:如何优雅地实现"只更新有值字段"
爬虫
数据智能老司机20 小时前
精通 Python 设计模式——分布式系统模式
python·设计模式·架构
数据智能老司机21 小时前
精通 Python 设计模式——并发与异步模式
python·设计模式·编程语言
数据智能老司机21 小时前
精通 Python 设计模式——测试模式
python·设计模式·架构
数据智能老司机21 小时前
精通 Python 设计模式——性能模式
python·设计模式·架构
c8i21 小时前
drf初步梳理
python·django