【问题标题】:Using find_all in BeautifulSoup when the filter is based on two distinct elements当过滤器基于两个不同的元素时在 BeautifulSoup 中使用 find_all
【发布时间】:2023-01-12 07:58:18
【问题描述】:

目前,我这样做是为了仅当 div 中有一个 tf-match-analyst-verdict 元素时才传递,而 div 又应该包含一个名为 match-headerclass

matches = soup.find_all('div', attrs={"class": "match-header"})
for match in matches:
    if (match.find('tf-match-analyst-verdict')):

在创建 matches 对象时传递此需求以消除使用 if 的需求的正确方法是什么?

【问题讨论】:

  • 如果BS4的选择器语法支持:has(),可以使用soup.select('div.match-header:has(tf-match-analyst-verdict)')
  • 嗨@Barmar 它完美地解决了我的需求

标签: python beautifulsoup


【解决方案1】:

使用 select() 而不是 find_all()。然后你可以使用:has() 选择器。

matches = soup.select('div.match-header:has(tf-match-analyst-verdict)')

:has(selector) 表示元素包含与选择器匹配的后代。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-15
    • 2021-12-10
    • 2017-03-13
    • 2011-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-04
    相关资源
    最近更新 更多