Selenium+Firefox:页面ID存在性检测代码异常求助
问题分析与解决方案
你的代码有几个关键问题导致无论页面是否存在该ID都返回Not working,我来一步步帮你修正:
1. 函数无返回值且未正确调用
你的checkoutpage函数只是执行了查找元素的操作,但没有返回任何值(Python函数默认返回None)。而且你在判断时直接写了checkoutpage == True——这里的checkoutpage是函数本身,不是调用函数后的结果,这完全不是正确的用法。
2. Try-Except结构语法与逻辑错误
你的代码里try块的缩进、if语句的位置都不符合Python语法规范,同时异常捕获的逻辑也没有精准覆盖到元素找不到的场景。
修正后的代码
这里我给出两种写法,一种兼容旧版Selenium语法,另一种是新版Selenium的推荐写法:
写法1(兼容旧版Selenium)
from selenium.common.exceptions import NoSuchElementException def checkoutpage(): try: # 尝试查找元素,找到则返回True driver1.find_element_by_id('test') return True except NoSuchElementException: # 捕获元素不存在的特定异常,返回False return False # 调用函数并根据返回值判断输出 if checkoutpage(): print("Working") else: print("Not working")
写法2(新版Selenium推荐)
如果你的Selenium版本是4.x及以上,推荐使用By类来定位元素:
from selenium.webdriver.common.by import By from selenium.common.exceptions import NoSuchElementException def checkoutpage(): try: driver1.find_element(By.ID, 'test') return True except NoSuchElementException: return False if checkoutpage(): print("Working") else: print("Not working")
关键说明
- 我们把查找元素的逻辑放在函数内部的
try-except块里,专门捕获NoSuchElementException(这是Selenium找不到元素时抛出的特定异常,比捕获所有异常更严谨)。 - 找到元素时返回
True,找不到则返回False,这样调用函数后就能正确判断结果。 - 一定要调用函数(
checkoutpage()),而不是直接用函数对象去做比较。
内容的提问来源于stack exchange,提问作者Ogden
相关产品推荐
相关产品推荐

