How to click on the button when the textContext contains leading and trailing white-space characters?

跟風遠走 提交于 2020-03-23 08:50:11

问题


I'm trying to click on the following button using Selenium with python:

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

This is just a simple button which looks like this:

Code:

driver.find_element_by_id('sbmt').click()

This results in the following exception:

selenium.common.exceptions.ElementNotInteractableException: Message:
Element <button id="sbmt" name="_eventId_proceed" type="submit">
could not be scrolledinto view

So, I tried scrolling to the element using ActionChains(driver).move_to_element(driver.find_elements_by_id('sbmt')[1]).perform() before clicking the button.

(Accessing the second element with [1] because the first would result in selenium.common.exceptions.WebDriverException: Message: TypeError: rect is undefined exception.).

Then I used

wait = WebDriverWait(driver, 5)
submit_btn = wait.until(EC.element_to_be_clickable((By.ID, 'sbmt')))

in order to wait for the button to be clickable. None of this helped.

I also used driver.find_element_by_xpath and others, I tested it with Firefox and Chrome.

How can I click on the button without getting an exception?

Any help would be greatly appreciated


回答1:


To invoke click() on the element you need to first use WebDriverWait with expected_conditions for the element to be clickable and you can use the following solution:

  • Using XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@id='sbmt' and normalize-space()='Einloggen']"))).click()
    
  • Note : You have to add the following imports :

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    


来源:https://stackoverflow.com/questions/54053154/how-to-click-on-the-button-when-the-textcontext-contains-leading-and-trailing-wh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!