【问题标题】:Get value using lxml使用 lxml 获取价值
【发布时间】:2015-04-09 22:33:31
【问题描述】:

我有以下html:

<div class="txt-block">
<h4 class="inline">Aspect Ratio:</h4> 2.35 : 1
</div>

我想从内容中获取值“2.35 : 1”。但是,当我尝试使用 lxml 时,它返回一个空字符串(我能够获得“纵横比”值,可能是因为它恰好位于标签之间。)

item.find('div').text

然后我将如何获得“2.35 : 1”值?使用 etree.tostring 确实可以得到完整的输出。

【问题讨论】:

    标签: python html html-parsing lxml lxml.html


    【解决方案1】:

    这称为元素的.tail

    from lxml.html import fromstring
    
    data = """
    <div class="txt-block">
    <h4 class="inline">Aspect Ratio:</h4> 2.35 : 1
    </div>
    """
    
    root = fromstring(data)
    print root.xpath('//h4[@class="inline"]')[0].tail
    

    打印2.35 : 1

    作为替代方案,您可以获取h4 元素的以下文本兄弟

    root.xpath('//h4[@class="inline"]/following-sibling::text()')[0] 
    

    此外,请确保您使用的是lxml.html,因为您正在处理 HTML 数据。

    【讨论】:

      【解决方案2】:

      您也可以使用.text_content(),而不是.text,这将为您提供元素的整个文本内容(http://lxml.de/lxmlhtml.html)--

      >>> item.find('div').text.text_content()
      Aspect Ratio: 2.35 : 1
      

      完整的陈述将是:

      >>> title_detail.text_content().split('Aspect Ratio: ')[1].strip()
      2.35 : 1
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-06-13
        • 2019-04-08
        • 1970-01-01
        • 2014-01-17
        • 1970-01-01
        • 2018-09-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多