如何在BeautifulSoup的find_all中通过双元素过滤去除if判断?
match-header Divs Directly for Child Elements Instead of first fetching all match-header divs and then checking each one, you can use BeautifulSoup's CSS selector with the :has() pseudo-class to get only the divs that contain a tf-match-analyst-verdict element right away. This eliminates the need for the separate if check.
Here's the updated code:
matches = soup.select('div.match-header:has(tf-match-analyst-verdict)')
How this works:
div.match-headertargets all div elements with the classmatch-header.- The
:has(tf-match-analyst-verdict)pseudo-class narrows this down to only those divs that contain at least onetf-match-analyst-verdictelement as a descendant (child, grandchild, etc.).
Note: Make sure you're using BeautifulSoup version 4.7.0 or newer—the :has() selector was added in this release. If you're on an older version, upgrade first with:
pip install --upgrade beautifulsoup4
If you prefer sticking with find_all instead of select, you can pass a custom filter function:
def has_verdict(tag): return tag.name == 'div' and 'match-header' in tag.get('class', []) and tag.find('tf-match-analyst-verdict') is not None matches = soup.find_all(has_verdict)
This function checks three conditions: the tag is a div, it has the match-header class, and it contains the desired child element. Either method will give you the filtered list directly, so you can skip the loop with the if check entirely.
内容的提问来源于stack exchange,提问作者Digital Farmer

