python - 当文本内容包含前导和尾随空白字符时如何单击按钮?

标签 python selenium selenium-webdriver

我正在尝试使用 Selenium 和 python 单击以下按钮:

<button type="submit" tabindex="4" id="sbmt" name="_eventId_proceed">
          Einloggen
</button>

这只是一个简单的按钮,如下所示:

enter image description here

代码:

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(),您需要首先使用 WebDriverWaitexpected_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/

相关文章:

javascript - iframe下#document的处理方法

python - 获取嵌套字典

python - 将类方法作为回调传递(面向对象编程 Python)

python - python中关键字参数值的命名空间是什么?

java - WebElement 或 WebDriver 来调用 findElement 方法?

java - 如何通过 Selenium 和 Java 使用 setCapability() 忽略 Internet Explorer 的保护模式设置?

selenium - 提交按钮在 Selenium webdriver 中不起作用

Python:从csv中逐行提取关键字

xml - 如何在没有testng.xml文件的情况下执行Testng和Maven

python - Selenium/Python 类型错误 : 'WebElement' object is not iterable