【问题标题】:how to grab alternating child tags in python beautifulsoup如何在python beautifulsoup中获取交替的子标签
【发布时间】:2014-11-28 17:59:08
【问题描述】:

我正在尝试从 html 页面中的交替标签中获取一系列数据。 html 看起来像这样:

<div>
    <h3>title</h3>
    <div>text</div>
    <h3>title</h3>
    <div>text</div>
    ...
</div>

由于我无法在“for each pair in div”中抓取每个 h3/div 对,我如何有效地抓取它们?

【问题讨论】:

    标签: python python-3.x beautifulsoup


    【解决方案1】:

    找到所有标题,然后从那里获取next sibling

    for header in soup.select('div h3'):
        next_div = header.find_next_sibling('div')
    

    element.find_next_sibling() 返回一个元素,如果找不到这样的同级元素,则返回 None

    演示:

    >>> from bs4 import BeautifulSoup
    >>> soup = BeautifulSoup('''\
    ... <div>
    ...     <h3>First header</h3>
    ...     <div>First div to go with a header</div>
    ...     <h3>Second header</h3>
    ...     <div>Second div to go with a header</div>
    ... </div>
    ... ''')
    >>> for header in soup.select('div h3'):
    ...     next_div = header.find_next_sibling('div')
    ...     print(header.text, next_div.text)
    ... 
    First header First div to go with a header
    Second header Second div to go with a header
    

    【讨论】:

      【解决方案2】:

      有很多方法可以做到这一点,但对我来说最简单的方法是选择所有 h3 标记,然后遍历 DOM 以获取它们的下一个兄弟。

      【讨论】:

        猜你喜欢
        • 2020-12-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-29
        • 2021-08-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多