【问题标题】:Search in HTML document with Python and lxml upwards使用 Python 和 lxml 向上搜索 HTML 文档
【发布时间】:2016-02-25 12:39:15
【问题描述】:

我有一个结构如下的 HTML 文档:

<html>
  <li>
     <a href="" />a1</a>
     <other tags ... />
     <li>
        <a href="">a2</a>
        <another one tag ... />
        <a name=3>
     </li>
  </li>
  <li>
    ...
  </li>

我需要找到位于 li 元素下的所有父 a 元素,并使用 name= 为 a 元素构建路径3。在这个例子中,它应该是 a1/a2。我使用 lxml 并编写了这个 Python 代码:

import lxml
...

def get_path_for_series(self, html, series):
    current = html.xpath('//a[@name="%s"]' % series)[0]
    path = list()
    while True:
        category = current.xpath('.//ancestor::li[1]//a[1]')
        if len(category) == 0:
            break
        path.append(self.clear(category[0].text_content()))
        current = category[0]
    return '/'.join(path)

它正确地找到了第一个元素,但是我有一个无限循环。我做错了什么?

【问题讨论】:

    标签: python html lxml


    【解决方案1】:

    您的 while 循环首先遍历祖先 li 并获取后代 a[1]。然后从当前a 开始,在下一个循环中,您的 XPath 将再次遍历到相同的li 祖先并返回相同的a 元素,这将永远持续下去(添加print current 进行验证。我看到了Element在同一个内存位置,这意味着它们是同一个实例,被一遍又一遍地打印)。

    您可以尝试从目标 a[@name="%s"] 向上移动树,然后像这样反向加入收集的路径步骤:

    def get_path_for_series(self, html, series):
        current = html.xpath('//a[@name="%s"]' % series)[0]
        path = list()
        parent = current.xpath('parent::li')
    
        while parent:
            a = parent[0].xpath('a[1]')[0]
            path.append(a.text)
            parent = parent[0].xpath('parent::li')
    
        # join `path` in reversed order
        return '/'.join(path[::-1])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-11
      • 2018-11-28
      • 2013-08-23
      • 2015-08-23
      相关资源
      最近更新 更多