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()
相关推荐
ponponon36 分钟前
时代的眼泪,nameko 和 eventlet 停止维护后的项目自救,升级和替代之路
python
Flittly37 分钟前
【从零手写 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