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

Python Selenium运行报NoSuchElementException无法定位username元素求助

报错原因排查
  • 核心报错NoSuchElementException的根本原因是:调用driver.get()后页面未完成渲染就立即执行元素查找逻辑,GST官网存在资源加载延迟、前端动态渲染逻辑,未等待加载完成必然找不到对应id的用户名输入框。
  • 代码存在多处语法和逻辑错误:
    1. 登录按钮的XPATH语法错误,缺少闭合符号,且选择器规则不规范
    2. 变量名拼写错误:定义的变量是login_button,后续调用写为login_buttion
    3. 重复触发登录操作:已经调用了click()方法,不需要再执行submit()
  • 打印的USB设备报错是Chrome浏览器的系统级警告,和Selenium运行逻辑无关,不影响脚本功能,可通过配置Chrome启动参数屏蔽。
修复后可运行代码
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from getpass import getpass

username = input("name:")
password = getpass("Enter your password")

# 配置Chrome选项,屏蔽无用日志
chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option("excludeSwitches", ["enable-logging"])

# 初始化驱动器,Selenium 4.x以上可以不用写executable_path,只要chromedriver在环境变量里
driver = webdriver.Chrome(
    executable_path="C:\\av\\chromedriver.exe",
    options=chrome_options
)

driver.get("https://services.gst.gov.in/services/login")

# 显式等待最多10秒,直到用户名输入框加载完成
wait = WebDriverWait(driver, 10)
username_textbox = wait.until(EC.presence_of_element_located((By.ID, "username")))
username_textbox.send_keys(username)

password_textbox = wait.until(EC.presence_of_element_located((By.ID, "user_pass")))
password_textbox.send_keys(password)

# 修正XPATH,等待登录按钮可点击后触发点击
login_button = wait.until(EC.element_to_be_clickable((By.XPATH, "//button[contains(text(), 'Login')]")))
login_button.click()
额外注意事项
  • 若运行后仍触发元素找不到的报错,可以手动打开GST登录页面,检查用户名输入框的id是否真的为username,部分地区的GST站点可能存在前端元素id调整的情况
  • 建议保持chromedriver版本和本地Chrome浏览器版本完全匹配,你当前用的是Chrome 93,要对应下载v93版本的chromedriver,避免版本不兼容导致的元素识别异常

内容的提问来源于stack exchange,提问作者Avesh Kumar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 23:30:02