zoukankan      html  css  js  c++  java
  • [XPath] XPath 与 lxml (五)XPath 实例

    本文继续沿用第三章的 XML 示例文档。

    选取价格高于30的 price 节点

    # 从父节点进行筛选
    >>> root.xpath('//book[price>30]/price')
    [<Element price at 0x2d888c8>]
    
    # 直接对 price 进行筛选
    >>> root.xpath('//price[text()>30]')
    [<Element price at 0x2d888c8>]

    选取 price 高于 30 的 title 节点

    # 从父节点开始选取
    >>> root.xpath('//book[price>30]/title')
    [<Element title at 0x2d88878>]
    
    # 从节点本身选取
    >>> root.xpath('//price[text()>30]//preceding-sibling::title|following-sibling::title')
    [<Element title at 0x2d88878>]
    
    # 从 price 到父节点选取
    >>> root.xpath('//price[text()>30]//parent::*/title')
    [<Element title at 0x2d88878>]

    处理命名空间

    >>> xml = """<?xml version="1.0" encoding="utf8"?>
    <bookstore xmlns:a="http://www.google.com">
        <a:book>
            <title lang="eng">Harry Potter</title>
            <price>29.99</price>
        </a:book>
        <book>
            <title lang="eng">Learning XML</title>
            <price>39.95</price>
        </book>
    </bookstore>"""
    
    # 获取根节点
    >>> root = etree.fromstring(xml)
    
    # 选取不带命名空间的 book 元素
    >>> root.xpath('//book')
    [<Element book at 0x2d88940>]
    
    # 选取所有的 book 元素,无论是否含有命名空间
    # 其中 namespace 参数为一个字典对象,映射了命名空间前缀,本例中直接使用了文档原有的命名空间与前缀。
    >>> root.xpath('//a:book|//book', namespaces=root.nsmap)
    [<Element {http://www.google.com}book at 0x2d88878>, <Element book at 0x2d88940>]
  • 相关阅读:
    PHP的后期静态绑定
    php的clone 浅拷贝
    python 从文件导入分类
    Yii2 主从 数据库
    什么是 jsonp ?
    为speedphp最新版添加 仿Yii 的简易版 数据验证 支持不同场景,自定义回调
    redis入门指南-安装redis
    composer -vvv
    依赖注入
    yii2-user
  • 原文地址:https://www.cnblogs.com/ifantastic/p/3863892.html
Copyright © 2011-2022 走看看