Python 3.x 在Selenium Python中找不到元素
您好,我正在尝试使用selenium查找要单击的按钮。下面是我正在使用的HTML代码片段Python 3.x 在Selenium Python中找不到元素,python-3.x,selenium,xpath,css-selectors,webdriverwait,Python 3.x,Selenium,Xpath,Css Selectors,Webdriverwait,您好,我正在尝试使用selenium查找要单击的按钮。下面是我正在使用的HTML代码片段 <input type="button" id="runButton" class="button" value="Run Report" onclick="chooseRun()"> 我收到以下错误消息: NoSuchElementException: Message: Unable to find element with css selector == [id="runButton"]
<input type="button" id="runButton" class="button" value="Run Report" onclick="chooseRun()">
我收到以下错误消息:
NoSuchElementException: Message: Unable to find element with css selector == [id="runButton"]
不知道还有什么可以尝试的
查找元素最可能需要的是使用等待。在与元素交互之前,您需要留出时间让元素可见、可单击等。您可以在此处找到有关等待的信息: 摘自上述网站:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
elem = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "runButton"))
如果等待不起作用,那么元素可能在iframe中。您需要首先切换到该iframe,然后搜索元素以找到它
您将找到iframe,就像找到另一个元素一样,然后像这样切换到它:
iframe = driver.find_element_by_id("content_Iframe")
driver.switch_to.frame(iframe)
button = driver.find_element_by_id("runButton")
button.click()
完成iframe及其内容后,需要切换回iframe:
driver.switch_to.default_content()
元素似乎是一个动态元素,因此要在元素上单击(),您需要使用
element\u to\u be\u clickable()
,并且可以使用以下任一选项:
- 使用
:CSS\u选择器
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.button#runButton[value='Run Report']"))).click()
- 使用
:XPATH
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='button' and @id='runButton'][@value='Run Report']"))).click()
- 注意:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC