【问题标题】:Selecting tags based on 2 consecutive tags using beautifulsoup使用beautifulsoup根据2个连续标签选择标签
【发布时间】:2017-01-19 01:57:00
【问题描述】:

我一直在尝试使用 find_all() 方法选择具有下一个元素为 p 的标签 h1,但我得到的是空列表。这是我的代码,

def has_h1_followedby_p(tag):
    return tag.name == 'h1' and tag.next_siblings.name == 'p'

soup = BeautifulSoup(open(filepath), 'html.parser')
h1_tags = soup.find_all(has_h1_followedby_p)

我想知道这种情况到底出了什么问题,因为它看起来很简单。我将非常感谢您提出任何建议。

【问题讨论】:

    标签: python-2.7 beautifulsoup


    【解决方案1】:

    next_siblings 是一个可以匹配所有下一个兄弟姐妹的生成器,而您需要一个:

    tag.name == 'h1' and tag.next_sibling and tag.next_sibling.name == "p"
    

    请注意,我们还应用了tag.next_sibling 真实性检查 - 可能会出现h1 没有下一个兄弟的情况。

    或者你可以搜索p下一个兄弟(虽然这和以前的版本不一样):

    tag.name == 'h1' and tag.find_next_sibling("p")
    

    【讨论】:

    • 感谢 alecxe 如此积极主动的回应,它就像一个魅力。
    猜你喜欢
    • 2017-02-21
    • 1970-01-01
    • 2017-05-04
    • 2019-04-26
    • 1970-01-01
    • 2019-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多