如何从BeautifulSoup.find()返回结果中获取可调用find_all的对象
BS4节点二次筛选问题解决方案
错误原因
你代码出错的核心原因是调用了.contents属性后,得到的是子节点组成的列表对象,而非BeautifulSoup的Tag节点对象,列表本身没有find_all方法,自然无法执行二次筛选。
正确实现方式
通过find拿到目标Tag节点后,直接在该节点上调用find、find_all等筛选方法即可,不需要额外调用.contents,BS4会自动在该节点的后代节点范围内执行筛选。
修正后代码示例:
import bs4 soup = bs4.BeautifulSoup(browser.page_source, "lxml") # 直接获取目标div节点,不要追加.contents competition_div = soup.find("div", class_="accordion-competition__content_main") # 直接在目标div节点上调用find_all做二次筛选 events = competition_div.find_all("div", class_="sport-event-card") for event in events: print("EVENT: ", event)
补充说明
如果确实需要基于.contents返回的子节点列表做筛选,注意.contents返回的列表中包含文本节点、注释节点等非Tag类型的元素,需要先判断节点类型再调用筛选方法:
for node in competition_div.contents: # 仅处理Tag类型的节点 if hasattr(node, 'find_all'): sub_nodes = node.find_all("你的目标选择器") # 后续处理逻辑
内容的提问来源于stack exchange,提问作者fholl124
相关产品推荐
相关产品推荐

