简体   繁体   English

Python:Selenium - 消息:元素不可交互

[英]Python: Selenium - Message: element not interactable

Novice trying to figure things out.新手想弄明白。 I've looked around for an answer and not found one.我四处寻找答案,但没有找到。
While trying to interact with a webpage, I get this message from Python:在尝试与网页交互时,我从 Python 收到此消息:

element not interactable元素不可交互

Here is my code:这是我的代码:

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
import time

PATH = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)

driver.get("https://www.annemcgilvray.com")

search = driver.find_element_by_name("q")

search.send_keys("test")

I've tried waiting and implicitly waiting.我试过等待和隐式等待。 I don't think it is in an iframe, though there are iframes on the page.我不认为它在 iframe 中,尽管页面上有 iframe。

Any help would be appreciated!任何帮助,将不胜感激!

When I tried your code, the problem was the the site did not adjust to the size of my browser window and the search field was out of view, and hence could not be interacted with, although selenium could locate it.当我尝试你的代码时,问题是网站没有调整到我的浏览器 window 的大小,搜索字段不在视野范围内,因此无法与之交互,尽管 selenium 可以找到它。

I tried using execute_script to scroll it into view, and after that, send_keys worked.我尝试使用execute_script其滚动到视图中,然后 send_keys 起作用了。

from selenium import webdriver

PATH = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)

driver.get("https://www.annemcgilvray.com")

search = wait.until(EC.visibility_of_element_located((By.NAME, "q")))

driver.execute_script(f"window.scrollBy({search.location['x']},0)")

search.send_keys("test")

You need to add wait / delay to let the element fully loaded before accessing it.您需要添加等待/延迟以让元素在访问之前完全加载。
The best approach is to use explicit wait implemented by expected conditions, as following:最好的方法是使用预期条件实现的显式等待,如下所示:

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

PATH = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)
wait = WebDriverWait(driver, 20)

driver.get("https://www.annemcgilvray.com")

search = wait.until(EC.visibility_of_element_located((By.NAME, "q")))

search.send_keys("test")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM