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

WebDriver无find_element_by_id属性报错求助(附注册自动化代码)

问题解决方案

错误原因

你使用的是Selenium 4.x版本,该版本已移除find_element_by_id、find_element_by_name这类旧版元素定位API,改用统一的find_element()方法配合By类实现元素定位。

修复步骤

  1. 导入By类:在代码顶部添加from selenium.webdriver.common.by import By
  2. 替换所有旧的定位方法,按以下规则修改:
    • find_element_by_id('xxx') → find_element(By.ID, 'xxx')
    • find_element_by_name('xxx') → find_element(By.NAME, 'xxx')
    • find_element_by_css_selector('xxx') → find_element(By.CSS_SELECTOR, 'xxx')
  3. 确保monster、phone、father_phone等变量已提前定义,避免运行时出现未定义错误。

修改后的完整代码

from selenium import webdriver
from selenium.webdriver.common.by import By

# 提前定义所需变量(示例值,根据实际需求修改)
monster = "TestName"
phone = "1234567890"
father_phone = "0987654321"
email = "test@example.com"
password = "TestPass123"
password_confirmation = "TestPass123"

driver = webdriver.Firefox()
driver.get('https://mahmoud-magdy.com/register')

driver.find_element(By.ID, 'first_name').send_keys(monster)
driver.find_element(By.ID, 'last_name').send_keys(monster)
driver.find_element(By.NAME, 'phone').send_keys(phone)
driver.find_element(By.NAME, 'father_phone').send_keys(father_phone)
driver.find_element(By.NAME, 'email').send_keys(email)
driver.find_element(By.NAME, 'password').send_keys(password)
driver.find_element(By.NAME, 'password_confirmation').send_keys(password_confirmation)
driver.find_element(By.CSS_SELECTOR, 'button[type="submit"]').click()

print(phone)
driver.quit()

内容的提问来源于stack exchange,提问作者Khaled Hegazy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 05:05:37