Selenium中if else语句失效及NoSuchElementException报错修复
修复Selenium中找不到元素时的异常问题
嘿,这个问题很常见!你遇到的核心问题是:driver.find_element_by_css_selector()方法在找不到元素时,不会返回False,而是直接抛出NoSuchElementException,所以你的if判断还没来得及执行,程序就直接报错终止了。
下面给你两种靠谱的修复方案:
方案1:使用try-except捕获异常(推荐)
这种方法更直观,专门处理元素找不到的异常情况,代码可读性更高:
from selenium.common.exceptions import NoSuchElementException # 先导入异常类 for i in range(1,21): try: # 尝试查找按钮并执行后续操作 next_btn = driver.find_element_by_css_selector('.sb_pagN_bp') next_btn.click() # 提取页面文本并写入文件 description = driver.find_elements_by_css_selector("p") with open(s_csv,'a',encoding="utf-8") as s: for desc in description: s.write(desc.text + '\n') except NoSuchElementException: # 找不到按钮时执行提示逻辑 nextp = 'There is no next button!' print(nextp) break # 没有下一页就跳出循环,避免无效重复
改动说明:
- 新增导入
NoSuchElementException类,用于精准捕获元素找不到的异常 - 把查找按钮和后续操作放进
try块,一旦触发异常就跳转到except块执行提示 - 加入
break(可选但推荐):既然已经没有下一页,继续循环20次毫无意义,直接跳出节省资源
方案2:使用find_elements判断元素是否存在
driver.find_elements_by_css_selector()方法找不到元素时会返回空列表,空列表在布尔判断中等价于False,这样就能正常走else分支:
for i in range(1,21): # 用find_elements返回元素列表,判断是否存在目标元素 next_btns = driver.find_elements_by_css_selector('.sb_pagN_bp') if next_btns: # 取列表第一个元素执行点击 next_btns[0].click() # 提取文本并写入文件 description = driver.find_elements_by_css_selector("p") with open(s_csv,'a',encoding="utf-8") as s: for desc in description: s.write(desc.text + '\n') else: nextp = 'There is no next button!' print(nextp) break
改动说明:
- 把
find_element替换为find_elements,得到一个元素列表 - 通过判断列表是否非空来决定执行逻辑,空列表则代表元素不存在
- 同样推荐加入
break跳出循环,避免无效执行
两种方案都能解决你的问题,个人更推荐第一种try-except的方式,因为它能精准处理“元素找不到”这个特定异常,避免其他意外情况被误判成“元素不存在”。
内容的提问来源于stack exchange,提问作者user12484897
相关产品推荐
相关产品推荐

