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()
相关推荐
Linux-lucky4 小时前
21-Linux学习之旅之HTTPS和安全加固
linux·运维·学习·ubuntu·https
CTA量化套保4 小时前
近期零基础量化学习:先分阶段,再用 AI 检查缺口
人工智能·python
清水白石0085 小时前
Python 死锁排查全攻略:从线程卡死到锁依赖定位与工程化修复
linux·网络·python
Elias不吃糖5 小时前
Langfuse 入门:Trace、Prompt、Dataset、Experiment、Evaluator
前端·python·prompt·langfuse
TechWayfarer6 小时前
批量查IP归属地,在线API、脚本、离线库怎么选?三种方案实测对比
网络·python·网络协议·tcp/ip
学运维的Kysan6 小时前
暑假运维学习打卡第二十六天8.17
学习
七牛开发者7 小时前
为什么 Go 很适合 AI 辅助开发?
数据库·人工智能·python·elasticsearch·log4j
dear_bi_MyOnly7 小时前
AI人工智能分类识别——机器如何学习
人工智能·学习·分类
河南凹凸环境艺术设计7 小时前
性价比高的民宿酒店设计企业
大数据·人工智能·python
启雀AI10 小时前
培训平台移动端离线学习方案设计与实现:视频缓存、断点续传与进度同步的工程实践
android·学习·缓存·音视频·企业lms