首页 > 解决方案 > 执行 send_key 或 clear() 时出现 InvalidElementStateException

问题描述

在此处输入图像描述

url='https://jwt.io/'
driver.get(url)
driver.execute_script("window.scrollTo(0, 1000)")
time.sleep(5)
element_data='/html/body/section[3]/div/div/div[3]/div[2]/div[2]/div/div[2]/div/div/div[4]'
#hightlight_body=\
element_data1=driver.find_element_by_xpath(element_data).clear()

错误:selenium.common.exceptions.InvalidElementStateException:消息:无效元素状态(会话信息:chrome=92.0.4515.159)

标签: pythonseleniumselenium-webdriver

解决方案


打开此站点时,会出现“接受 cookie”弹出窗口,因此您必须先将其关闭。
该元素位于 iframe 内。
因此,您首先必须切换到 iframe,关闭弹出窗口,切换到默认内容,然后您才能继续编写代码。
你的代码应该是这样的:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, 20)

url='https://jwt.io/'
driver.get(url)
wait.until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,'iframe[title="TrustArc Cookie Consent Manager"]')))
wait.until(EC.visibility_of_element_located((By.XPATH, '//a[contains(text(),'Accept All')]'))).click()
driver.switch_to.default_content()

driver.execute_script("window.scrollTo(0, 1000)")
time.sleep(5)
element_data='/html/body/section[3]/div/div/div[3]/div[2]/div[2]/div/div[2]/div/div/div[4]'
#hightlight_body=\
element_data1=driver.find_element_by_xpath(element_data).clear()

推荐阅读