• xpath 使用


    xpath 是数据提取的一种常用的方法

    参考
    XPath 是一门在 XML 文档中查找信息的语言。XPath 用于在 XML 文档中通过元素和属性进行导航。
    在 XPath 中,有七种类型的节点:元素、属性、文本、命名空间、处理指令、注释以及文档(根)节点。XML 文档是被作为节点树来对待的。树的根被称为文档节点或者根节点。

    选取节点

    XPath 使用路径表达式在 XML 文档中选取节点。节点是通过沿着路径或者 step 来选取的。
    下面列出了最有用的路径表达式:

    操作步骤:

    引入

    from lxml.html import etree
    

    创建文档树

    
    def HTML(text, parser=None, base_url=None): # real signature unknown; restored from __doc__
        """
        HTML(text, parser=None, base_url=None)
        
            Parses an HTML document from a string constant.  Returns the root
            node (or the result returned by a parser target).  This function
            can be used to embed "HTML literals" in Python code.
        
            To override the parser with a different ``HTMLParser`` you can pass it to
            the ``parser`` keyword argument.
        
            The ``base_url`` keyword argument allows to set the original base URL of
            the document to support relative Paths when looking up external entities
            (DTD, XInclude, ...).
        """
        pass
    
    html_obj = etree.HTML(html, parser=HTMLParser(encoding='utf-8'))
    

    用xpath提取数据

    div_obj = html_obj.xpath('//div[@class="l_post"]') # [@条件]
    divs = html_obj.xpath('//div[contains(@class, "l_post")]') #如果属性值有多个可用contains
    divs = html_obj.xpath('//div[@class="l_post"]/text()')  #取标签中的值时  text()
    divs = html_obj.xpath('//div[@class="l_post"]/a/@href') #取标签的属性值时  @属性名 
    

    xpath获取标签内的包括所有下级标签的所有文字内容

    参考
    现有html源码如下:

    <div>
        <ul class="1">
            <li>1</li>
            <li>12<a>bcd</a></li>
            <li>123</li>
            <li>1234</li>
        </ul>
        <ul class="2">
            <li>2</li>
            <li>22<a>efg</a></li>
            <li>223</li>
            <li>2234</li>
        </ul>
    </div>
    

    想要获取ul class="1"下所有的文字内容,即:

    1
    12 bcd
    123
    1234
    

    可通过xpath的string()函数实现

    from lxml import etree
    
    a = """<div>
        <ul class="1">
            <li>1</li>
            <li>12<a>bcd</a></li>
            <li>123</li>
            <li>1234</li>
        </ul>
        <ul class="2">
            <li>2</li>
            <li>22<a>bcd</a></li>
            <li>223</li>
            <li>2234</li>
        </ul>
    </div>
        """
    b = etree.HTML(a)
    c = b.xpath('string(//ul)')
    print(c)
    

    结果

    
         1
         12bcd
         123
         1234
    
  • 相关阅读:
    SpringFlex框架搭建
    SqlDataReader的用法 转自https://www.cnblogs.com/sunxi/p/3924954.html
    C#学习笔记:ListBox控件的用法
    C#栈Stack的使用
    C# 队列Queue
    xshell传送文件
    Java基础中字符串与字符的注意点!
    大数据的基础学习:
    Python的空行
    Python基本语法
  • 原文地址:https://www.cnblogs.com/wzbk/p/14741849.html
Copyright © 2020-2023  润新知