Python Selenium 自动化控制浏览器:解决 ElementNotInteractableException 问题在使用 Selenium 进行 Web 自动化测试时,经常会遇到 'ElementNotInteractableException: element not interactable' 错误。这意味着 Selenium 无法与页面上的某个元素进行交互,可能是因为元素还没有加载完成,或者被其他元素遮挡了。本文将通过一个实际案例,介绍如何使用 Python Selenium 库来自动化控制浏览器,并解决 'ElementNotInteractableException' 错误。### 案例背景假设我们需要在内蒙古开放大学的网站上自动输入学生成绩。我们可以使用 Selenium 自动化打开浏览器,登录网站,找到输入成绩的文本框,并输入随机生成的成绩。### 代码实现pythonimport osimport timeimport randomfrom selenium import webdriverfrom selenium.webdriver.chrome.options import Optionsfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECdef check_browser(): # 检查是否已经打开了浏览器 try: options = Options() options.add_experimental_option('debuggerAddress', '127.0.0.1:9527') browser = webdriver.Chrome(options=options) browser.execute_script('return true') return True except: return Falseif name == 'main': if not check_browser(): os.system(r'start chrome --remote-debugging-port=9527 --user-data-dir='D:/评阅用'') options = Options() options.add_experimental_option('debuggerAddress', '127.0.0.1:9527') browser = webdriver.Chrome(options=options) for handle in browser.window_handles: browser.switch_to.window(handle) if '内蒙古开放大学' in browser.title: break # 使用显式等待,等待元素可见并可交互 element = WebDriverWait(browser, 10).until( EC.element_to_be_clickable((By.NAME, 'score')) ) element.clear() score = random.randint(95, 99) element.send_keys(str(score)) print('输入成绩为:', score)### 代码解析1. 导入必要的库: - os 用于执行系统命令。 - time 用于暂停程序执行。 - random 用于生成随机数。 - selenium 用于控制浏览器。 - WebDriverWaitexpected_conditions 用于实现显式等待。2. check_browser() 函数: 检查是否已经打开了浏览器,如果打开了,就连接到已有的浏览器实例。3. 主程序: - 启动浏览器,并连接到内蒙古开放大学的网站。 - 使用 WebDriverWaitEC.element_to_be_clickable 实现显式等待,确保 'score' 元素可见并可交互。 - 清空 'score' 文本框的内容,生成一个随机成绩,并将其输入到文本框中。### 解决 ElementNotInteractableException在上面的代码中,我们使用了 WebDriverWaitEC.element_to_be_clickable 来实现显式等待。这意味着 Selenium 会等待最多 10 秒钟,直到 'score' 元素可见并可交互,才会继续执行后续操作。这有效地解决了 'ElementNotInteractableException' 错误。### 总结本文介绍了如何使用 Python Selenium 库来自动化控制浏览器,并通过一个实际案例讲解了如何解决 'ElementNotInteractableException' 错误。在进行 Web 自动化测试时,合理地使用显式等待可以有效提高脚本的稳定

Python Selenium 自动化控制浏览器:解决 ElementNotInteractableException 问题

原文地址: https://www.cveoy.top/t/topic/fYsW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录