为何BeautifulSoup的find_all无法找到已存在的div元素?
Why can't
find_all() locate the div that clearly exists? Let's break down exactly what's going on here:
- Your
searchResultvariable is the<div id="results-from-CIDR">element itself—just look at your first print output, which shows the full div content. - The
find_all()method in BeautifulSoup searches for descendant elements (children, grandchildren, etc.) of the tag you call it on. Since this div doesn't contain any other divs inside it (your empty[]results confirm this), runningfind_all("div")on it will return nothing. - When you tried
searchResult.find_all("div", attrs={"id":"results-from-CIDR"}), you're asking BeautifulSoup to look for a child div with that ID—but the tag you're calling this on is that very div, not a parent element containing it. So there's no matching descendant to find.
What to do instead:
If you need to work with this div, you don't need to search for it again—you already have it in searchResult! But here are a few relevant options depending on your goal:
- To confirm you have the right element, check its attributes directly:
if searchResult.get("id") == "results-from-CIDR": # Access its text or other properties print(searchResult.get_text(strip=True)) - If you want a list-like result (similar to
find_all()output) that includes this div, wrap it manually:target_divs = [searchResult] if searchResult.get("id") == "results-from-CIDR" else [] - If you originally retrieved
searchResultfrom a larger soup object, you should run yourfind()orfind_all()on the parent/soup level instead of the div itself:# Example using the full soup from bs4 import BeautifulSoup # Assuming 'html_content' is your raw HTML soup = BeautifulSoup(html_content, "html.parser") target_div = soup.find("div", id="results-from-CIDR")
内容的提问来源于stack exchange,提问作者Sebastian
相关产品推荐
相关产品推荐

