当textContext使用Selenium和Python包含前导和尾随空格字符时如何单击按钮

问题描述 投票:1回答:1

我正在尝试将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进行了测试。

如何在没有异常的情况下单击按钮?

任何帮助将不胜感激

python selenium selenium-webdriver xpath webdriverwait
1个回答
2
投票

要在元素上调用click(),您需要首先将WebDriverWaitexpected_conditions一起用于可单击的元素,然后可以使用以下解决方案:

  • 使用XPATH

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@id='sbmt' and normalize-space()='Einloggen']"))).click()
    
  • Note:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
© www.soinside.com 2019 - 2024. All rights reserved.