提问人:Tianyu Leng 提问时间:11/7/2023 更新时间:11/7/2023 访问量:51
如何解决硒中的“不可交互元素”?
How to resolve 'element not interactable' in selenium?
问:
我希望利用硒与网站进行交互。根据源的逻辑,在下拉菜单中指定项目之前,我可以继续进入其余下拉菜单。但是,在指定第一项后,其余菜单仍然不可交互。其余元素既不显示也不交互,即使设置了 display=“block”。如何解决这个问题?
我的代码如下:
import selenium.webdriver as wbd
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
import time
driver = wbd.Chrome() # may alter with browser
driver.get('http://wordvec.colorado.edu/matrix_comparison.html') # fixed
vector_type = driver.find_element(By.NAME, 'vector_type')
Select(vector_type).select_by_value("LSA")
time.sleep(1)
topic_space = driver.find_element(By.ID, "topic_space")
print(topic_space.is_displayed())
topic_space.send_keys("tasa") # fixed
time.sleep(1)
comparison_type = driver.find_element(By.NAME, 'comparison_type')
comparison_type.send_keys('document') # fixed
time.sleep(1)
num_factors = driver.find_element(By.NAME, 'num_factors')
num_factors.send_keys(str(30)) # set # or 100
time.sleep(1)
错误是:
消息:元素不可交互 (会话信息:chrome=119.0.6045.105)
答:
1赞
Shawn
11/7/2023
#1
问题出在下面一行:
topic_space = driver.find_element(By.ID, "topic_space")
如果您注意到 HTML,则有 3 个元素带有 .在您的案例中,所需的元素是第三个元素。您可以使用以下 XPATH 表达式来查找第三个元素 - 。ID=topic_space
(//select[@id='topic_space'])[3]
因此,请更改该代码行,如下所示:
topic_space = driver.find_element(By.XPATH, "(//select[@id='topic_space'])[3]")
更新:除上述问题外,您的代码还存在其他问题。像下面的代码不是正确的方法 - 选择一个下拉值。它应该是:。我已经解决了这些问题,并且还通过删除并应用了 Selenium 的 Waits(更有效)来重构您的代码。topic_space.send_keys("tasa")
Select(topic_space).select_by_value("tasa")
time.sleep()
检查以下重构代码:
import selenium.webdriver as wbd
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = wbd.Chrome() # may alter with browser
driver.get('http://wordvec.colorado.edu/matrix_comparison.html') # fixed
wait = WebDriverWait(driver, 20)
vector_type = wait.until(EC.element_to_be_clickable((By.NAME, "vector_type")))
Select(vector_type).select_by_value("LSA")
topic_space = wait.until(EC.element_to_be_clickable((By.XPATH, "(//select[@id='topic_space'])[3]")))
print(topic_space.is_displayed())
Select(topic_space).select_by_value("tasa")
comparison_type = wait.until(EC.element_to_be_clickable((By.NAME, 'comparison_type')))
Select(comparison_type).select_by_value("document")
num_factors = wait.until(EC.element_to_be_clickable((By.NAME, "num_factors")))
num_factors.send_keys(str(30)) # set # or 100
结果:
评论
0赞
Tianyu Leng
11/7/2023
非常感谢!它有效!
评论