BeautifulSoup搜索无结果报NoneType无find_all属性错误处理
报错根因
你触发的AttributeError: 'NoneType' object has no attribute 'find_all'来自无校验的链式调用:当搜索无结果时,页面不存在class为result-list的<ul>元素,soup.find()会直接返回None,后续对None执行find_all('li')就会抛出异常,中断整个循环。
解决方案
优先用非空预判的写法处理,逻辑清晰且不会误捕获其他场景的同名异常,不推荐上来就全段加异常捕获。
方案1:拆分链式调用,提前做非空判断
把原来一行的链式调用拆成两步,先判断结果列表容器是否存在,再执行后续解析,不存在就直接跳过当前搜索词进入下一轮循环:
# 替换原来的 soup.find('ul', {'class':'result-list'}).find_all('li') 写法 result_list_container = soup.find('ul', {'class':'result-list'}) result_items = [] if result_list_container: # 确认容器存在再提取li元素 result_items = result_list_container.find_all('li') else: # 这里可以打印日志记录无结果的搜索词,然后直接continue进下一轮循环 print(f"搜索词无匹配结果,跳过解析") continue
方案2:定向捕获AttributeError
如果你的页面结构变动比较频繁,也可以直接捕获对应异常,注意不要写裸的except:,避免吞掉其他意料之外的报错:
result_items = [] try: result_items = soup.find('ul', {'class':'result-list'}).find_all('li') except AttributeError: # 仅捕获找不到元素触发的属性错误 print(f"搜索词无匹配结果,跳过解析") continue
Selenium+BeautifulSoup 完整循环参考
适配现有技术栈的循环逻辑片段,替换原有解析部分即可:
from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from bs4 import BeautifulSoup import time # driver初始化逻辑保留你原有代码即可 search_keywords = ["关键词1", "关键词2", "关键词3"] # 替换成你的搜索词列表 for keyword in search_keywords: # 以下搜索操作替换成目标站点的实际交互逻辑 driver.get("目标站点搜索页地址") # 定位搜索框、输入关键词、提交搜索 search_box = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, "搜索框ID")) # 替换成站点搜索框的实际定位规则 ) search_box.clear() search_box.send_keys(keyword) search_box.submit() # 建议用显式等待代替固定sleep,等页面内容加载完成再解析,避免加载不完全导致的误判 time.sleep(1.5) # 不想写显式等待可保留固定等待 # 解析页面 soup = BeautifulSoup(driver.page_source, "html.parser") result_container = soup.find("ul", class_="result-list") if not result_container: print(f"[提示] 搜索词 {keyword} 无匹配结果,自动跳过") continue # 正常解析结果项 item_list = result_container.find_all("li") for item in item_list: # 这里写提取标题、链接、摘要等字段的自定义逻辑 # title = item.find("h3").text.strip() # link = item.find("a")["href"] pass # 所有搜索词遍历完成后再退出driver driver.quit()
额外提示:如果站点的无结果页有固定的提示文案/专属元素,也可以优先判断无结果标识是否存在,逻辑会更严谨。
内容的提问来源于stack exchange,提问作者robebo
相关产品推荐
相关产品推荐

