Selenium测试中Python点击函数遇NoneType及语法错误求助
Selenium报错解决与新语法迁移
错误原因分析
PyCharm报错:
AttributeError: 'WebDriver' object has no attribute 'find_element_by_css_selector'
Selenium 4.0版本起彻底废弃了find_element_by_xxx这类旧版元素定位方法,统一改用基于By枚举类的新API,IDE能检测到旧方法已被移除,因此抛出该错误。CMD报错:
AttributeError: 'NoneType' object has no attribute 'click'
两种核心诱因:self.driver未被正确初始化(比如BaseClass中的启动逻辑缺失,导致driver实例为None);- 元素定位器不准确,找不到目标元素,
find_element返回None后调用click()触发报错。
完整修改后的代码
import pytest from selenium import webdriver import time from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from utilities.BaseClass import BaseClass class TestOne(BaseClass): def test_e2e(self): # 替换旧版CSS选择器定位方法 self.driver.find_element(By.CSS_SELECTOR, "a[href*='shop']").click() # 替换旧版复数元素定位方法 cards = self.driver.find_elements(By.CSS_SELECTOR, ".card-title a") i = -1 for card in cards: i = i + 1 cardText = card.text print(cardText) if cardText == "Blackberry": self.driver.find_elements(By.CSS_SELECTOR, ".card-footer button")[i].click() self.driver.find_element(By.CSS_SELECTOR, "a[class*='btn-primary']").click() # 修复笔误并替换为XPATH新API self.driver.find_element(By.XPATH, "//button[@class='btn btn-success']").click() self.driver.find_element(By.ID, "country").send_keys("ind") element = WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.LINK_TEXT, "India"))) self.verifyLinkPresence("India") self.driver.find_element(By.LINK_TEXT, "India").click() self.driver.find_element(By.XPATH, "//div[@class='checkbox checkbox-primary']").click() self.driver.find_element(By.CSS_SELECTOR, "[type='submit']").click() textMatch = self.driver.find_element(By.CSS_SELECTOR, "[class*='alert-success']").text assert ("Success! Thank you!" in textMatch)
关键修改点清单
- 全量替换旧版定位方法为新API:
旧方法 新API写法 find_element_by_css_selector("xxx")find_element(By.CSS_SELECTOR, "xxx")find_elements_by_css_selector("xxx")find_elements(By.CSS_SELECTOR, "xxx")find_element_by_xpath("xxx")find_element(By.XPATH, "xxx")find_element_by_id("xxx")find_element(By.ID, "xxx")find_element_by_link_text("xxx")find_element(By.LINK_TEXT, "xxx") - 修复原代码笔误:
find_element_by_css_xpath为错误写法,替换为find_element(By.XPATH, ...) - 检查
BaseClass初始化逻辑:确保测试前通过setup_method或pytest fixture正确创建driver实例,示例:class BaseClass: def setup_method(self): self.driver = webdriver.Chrome() # 根据使用的浏览器选择对应驱动 self.driver.maximize_window()
额外注意事项
- 确保浏览器驱动(如ChromeDriver)版本与本地浏览器版本匹配;
- 对所有元素操作优先使用显式等待(
WebDriverWait),避免页面加载延迟导致的定位失败; - 若仍出现
NoneType错误,可先打印self.driver确认实例是否存在,或用浏览器开发者工具验证定位器的准确性。
内容的提问来源于stack exchange,提问作者LightSL
相关产品推荐
相关产品推荐

