您好,我正在尝试使用硒来查找要单击的按钮。以下是我正在使用的HTML代码的片段。
<input type="button" id="runButton" class="button" value="Run Report" onclick="chooseRun()">
我正在尝试使用以下代码单击runButton。
elem = driver.find_element_by_id('runButton').click()
我收到以下错误消息:
NoSuchElementException: Message: Unable to find element with css selector == [id="runButton"]
不知道还有什么尝试。
该元素似乎是一个动态元素,因此要对该元素上的click()
使用element_to_be_clickable()
,并且可以使用以下Locator Strategies之一:
使用CSS_SELECTOR
:
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
最可能需要查找元素的方法是使用等待。您需要花时间让元素可见,可点击等,然后才能与它进行交互。您可以在这里找到有关等待的信息:https://selenium-python.readthedocs.io/waits.html
摘自上述网站:
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及其内容的处理,您将需要切换回它:
driver.switch_to.default_content()