You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Selenium报错:WebDriver.find_element_by_id()参数个数不符求助

问题分析与解决方案

错误原因

你遇到的报错是因为Selenium 4.x 已彻底移除了find_element_by_id、find_element_by_link_text这类旧版定位API,同时你自行添加的自定义find_element_by_id方法参数定义错误(缺少self参数,导致调用时传入的元素ID被当作第二个位置参数,而方法只定义了1个参数)。

解决步骤

不需要自定义WebDriver方法,直接使用Selenium 4.x的标准定位方式即可:

  1. 导入By类:用于指定定位策略
  2. 替换旧API为新格式:用driver.find_element(By.定位方式, 定位值)替代旧方法
  3. 确保Selenium为最新版本:如果版本过低,执行更新命令

更新Selenium(若版本<4.0)

pip install --upgrade selenium

修正后的代码

from selenium import webdriver
from selenium.webdriver.common.by import By  # 新增导入By类
import time

driver = webdriver.Chrome() 
driver.implicitly_wait(10)
driver.maximize_window()
driver.get("https://opensource-demo.orangehrmlive.com/")

# 替换旧的find_element_by_id为新格式
driver.find_element(By.ID, 'username').send_keys("Admin")
driver.find_element(By.ID, 'password').send_keys("admin123")
# 原代码中link_text定位无效,OrangeHRM登录按钮实际是按钮元素,改用ID定位
driver.find_element(By.ID, 'btnLogin').click()

time.sleep(2)
driver.close()
driver.quit()
print("Test Completed")

补充说明

  • Selenium 4.x之后所有元素定位统一使用find_element()和find_elements()方法,配合By类枚举值(如By.ID、By.NAME、By.XPATH等)
  • 原代码中find_element_by_link_text('login')定位逻辑错误,目标登录按钮并非链接文本元素,使用By.ID, 'btnLogin'是更可靠的定位方式

内容的提问来源于stack exchange,提问作者Usman Tariq

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 12:32:10