Python Selenium自动化: 解决'element not interactable'错误
Python Selenium自动化: 解决'element not interactable'错误在使用Selenium进行Web自动化测试时,你可能会遇到'element not interactable'错误。这个错误通常意味着Selenium无法与页面上的某个元素进行交互,因为它还没有加载完成或者被其他元素遮挡。本文将介绍如何使用Python Selenium解决这个错误,并提供一个具体的代码示例。### 错误分析'element not interactable'错误通常是由于以下原因造成的:* 元素尚未加载完成: 当Selenium尝试与一个尚未加载完成的元素交互时,就会出现这个错误。* 元素被遮挡: 如果目标元素被其他元素(例如,一个模态框)遮挡,Selenium就无法与其交互。### 解决方法:使用显式等待为了解决这个问题,我们可以使用Selenium的显式等待功能。显式等待会告诉Selenium等待特定的条件满足后再继续执行代码。以下是如何使用显式等待来解决'element not interactable'错误的示例: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 # 使用WebDriverWait等待元素加载完成 element = WebDriverWait(browser, 10).until( EC.presence_of_element_located((By.NAME, 'score')) ) element.clear() score = random.randint(95, 99) element.send_keys(str(score)) print('输入成绩为:', score)在这个例子中,我们使用了WebDriverWait和expected_conditions模块。 WebDriverWait(browser, 10)会等待最多10秒钟,直到EC.presence_of_element_located((By.NAME, 'score'))条件满足。这个条件会在页面中出现名为'score'的元素时满足。### 总结'element not interactable'错误是Selenium自动化测试中常见的错误之一。通过使用显式等待,我们可以确保Selenium在与元素交互之前等待元素加载完成,从而避免这个错误。
原文地址: https://www.cveoy.top/t/topic/fYta 著作权归作者所有。请勿转载和采集!