【问题标题】:Python - BeautifulSoup findParent by attributePython - BeautifulSoup 按属性查找父级
【发布时间】:2015-02-16 16:30:53
【问题描述】:

我希望在 BeautifulSoup 中使用 findParent() 方法来查找具有 id 属性的特定标签的父级。例如,考虑以下示例 XML:

<monograph>
    <section id="1234">
        <head>Test Heading</head>
        <p>Here's a paragraph with some text in it.</p>
    </section>
</monograph>

假设我已经匹配了段落中的某些内容,我想使用 findParent 不加选择地在树上找到具有 id 属性的第一个父级。比如:

 for hit in monograph(text="paragraph with"):
     containername = hit.findParent(re.compile([A-Za-z]+), {id}).name

但是,前面的代码没有返回任何命中。

【问题讨论】:

    标签: python python-3.x beautifulsoup


    【解决方案1】:

    使用id=True 匹配具有id 属性的元素,无论该属性的值如何:

    hit.find_parent(id=True)
    

    相反,使用id=False 会发现第一个父元素没有 id 属性。

    请注意,对于 BeautifulSoup 方法,您应该真正使用 lower_case_with_underscores 样式; findParent 是 BeautifulSoup 3 的拼写,has been deprecated

    演示:

    >>> from bs4 import BeautifulSoup
    >>> sample = '''\
    ... <monograph>
    ...     <section id="1234">
    ...         <head>Test Heading</head>
    ...         <p>Here's a paragraph with some text in it.</p>
    ...     </section>
    ... </monograph>
    ... '''
    >>> soup = BeautifulSoup(sample, 'xml')
    >>> str(soup.p)
    "<p>Here's a paragraph with some text in it.</p>"
    >>> print(soup.p.find_parent(id=True).prettify())
    <section id="1234">
     <head>
      Test Heading
     </head>
     <p>
      Here's a paragraph with some text in it.
     </p>
    </section>
    
    >>> print(soup.p.find_parent(id=False).prettify())
    <monograph>
     <section id="1234">
      <head>
       Test Heading
      </head>
      <p>
       Here's a paragraph with some text in it.
      </p>
     </section>
    </monograph>
    

    【讨论】:

      猜你喜欢
      • 2013-07-28
      • 1970-01-01
      • 1970-01-01
      • 2022-07-18
      • 2020-12-15
      • 2016-01-08
      • 2018-05-04
      • 2020-03-14
      • 2017-08-03
      相关资源
      最近更新 更多