我正在尝试使用 Selenium 和 python 单击以下按钮:
<button type="submit" tabindex="4" id="sbmt" name="_eventId_proceed">
Einloggen
</button>
这只是一个简单的按钮,如下所示:
代码:
driver.find_element_by_id('sbmt').click()
这会导致以下异常:
selenium.common.exceptions.ElementNotInteractableException: Message:
Element <button id="sbmt" name="_eventId_proceed" type="submit">
could not be scrolledinto view
因此,在单击按钮之前,我尝试使用 ActionChains(driver).move_to_element(driver.find_elements_by_id('sbmt')[1]).perform()
滚动到该元素。
(使用 [1]
访问第二个元素,因为第一个元素会导致 selenium.common.exceptions.WebDriverException: Message: TypeError: rect is undefined
异常。) .
然后我用了
wait = WebDriverWait(driver, 5)
submit_btn = wait.until(EC.element_to_be_clickable((By.ID, 'sbmt')))
为了等待按钮可点击。这些都没有帮助。
我还使用了 driver.find_element_by_xpath
等,我用 Firefox 和 Chrome 进行了测试。
如何点击按钮而不出现异常?
任何帮助将不胜感激
最佳答案
要在元素上调用 click()
,您需要首先使用 WebDriverWait 和 expected_conditions
以使元素可点击 您可以使用以下解决方案:
使用
XPATH
:WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@id='sbmt' and normalize-space()='Einloggen']"))).click()
注意:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
关于python - 当文本内容包含前导和尾随空白字符时如何单击按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54053154/