【问题标题】:How to get first element with the given href faster如何更快地获得具有给定href的第一个元素
【发布时间】:2012-05-25 06:45:21
【问题描述】:

我有一个工作示例,它生成具有给定 href 的 html 元素列表。但是我只需要第一个,速度很重要,如何优化这段代码?

import lxml.html
input = """<div class="post" style="height: 36px; ">
some div text 
<a href="http://site.com/" target="_blank">Look here</a>, 
some div text also </div>
"""
root = lxml.html.fromstring(input)
el = root.xpath("//*[@href='http://site.com/']")[0]
el.text

【问题讨论】:

    标签: python-2.7 lxml


    【解决方案1】:

    您可以在 xpath 表达式中使用索引:(//*[@href='http://site.com/'])[1]

    【讨论】:

      【解决方案2】:

      确保它确实更快的唯一方法是测量、测量、测量。 timeit module 可以提供帮助。

      回到你的问题,这个怎么样?

      text = root.xpath('//*[@href='http://site.com/'][1]/text()')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多