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

使用Selenium自动表单填充时遭遇ElementNotVisibleException错误

解决Selenium的ElementNotVisibleException错误(element not visible)

嘿,我一眼就看到问题出在哪了——你的等待条件写反啦!

你现在的代码里写了这么一行:

wait.until(lambda driver: driver.find_element_by_id('txt_username').is_displayed() == False)

这是在等待用户名输入框变成不可见,但紧接着你就要去点击、输入这个元素,这时候元素还没加载显示出来,自然就会抛出ElementNotVisibleException了。

修复方案

把等待条件改成等待元素可见,确保后续操作时元素已经正常显示在页面上。另外推荐用Selenium官方的expected_conditions工具类,比自己写lambda表达式更规范可靠:

修正后的完整代码:

from urllib import parse
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

class ICAIScraper(object):
    def __init__(self):
        self.url = "https://www.icaionlineregistration.org/Admin_Module/Login.aspx"
        self.driver = webdriver.Chrome('C:\\chromedriver.exe')
        
    def scrape(self):
        self.driver.get(self.url)
        wait = WebDriverWait(self.driver, 10)
        # 等待用户名输入框可见,用EC工具类更稳妥
        wait.until(EC.visibility_of_element_located((By.ID, 'txt_username')))
        
        print('Yay! on the first page')
        username = self.driver.find_element_by_id('txt_username')
        username.click()
        username.send_keys('username')
        
        password = self.driver.find_element_by_id('txt_password')
        password.send_keys('password')
        password.send_keys(Keys.ENTER)
        
        self.driver.quit()

if __name__ == '__main__':
    scraper = ICAIScraper()
    scraper.scrape()

额外小提示

  • 一定要保证ChromeDriver和你的Chrome浏览器版本匹配,版本不兼容也可能引发各种奇怪的元素交互问题;
  • 如果页面有弹窗、加载遮罩或者iframe,也要先处理这些干扰项,再操作目标元素;
  • 后续如果遇到类似元素交互问题,可以先手动打开页面观察加载流程,看看元素是不是需要滚动、点击其他按钮才会显示。

内容的提问来源于stack exchange,提问作者Maha Purush

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:56:20