Python Selenium使用EC.presence_of_element_located报NameError求助
报错原因
NameError: name 'EC' is not defined的核心原因是未导入Selenium的预期条件模块,EC是社区约定俗成的selenium.webdriver.support.expected_conditions模块别名,未导入时Python无法识别该标识符,就会抛出命名错误。
解决方法
在代码开头添加对应导入语句即可:
from selenium.webdriver.support import expected_conditions as EC
如果其他用到的依赖也未导入,可参考完整导入列表:
from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC
额外优化提示
当前代码里使用By.CLASS_NAME传入了多类名字符串VjDLd mnr-c g-blk,而By.CLASS_NAME仅支持单个类名匹配,后续会触发元素找不到的错误。如果需要匹配同时包含三类名的元素,可改用CSS选择器写法:
unnecessary = WebDriverWait(browser, 5).until(EC.presence_of_element_located((By.CSS_SELECTOR,".VjDLd.mnr-c.g-blk")))
内容的提问来源于stack exchange,提问作者Seowoo Jang
相关产品推荐
相关产品推荐

