1

I want to click the button in the modal that opens when I press the button, but it gives an error

my code:

driver.find_element_by_xpath('//*[@id="buy-now-button"]').click()
sleep(5)
x = driver.find_elements_by_xpath("//*[@id='turbo-checkout-pyo-button']")
if len(x) > 0:
    y = driver.find_element_by_xpath("//*[@id='turbo-checkout-pyo-button']")
    y.click()

error:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id='turbo-checkout-pyo-button']"}

screenshot

5
  • 1
    Is it in an iframe? or do you need a webdriverwait to ensure your button is available on the page before you attempt to access it? Commented Mar 4, 2021 at 16:40
  • @RichEdwards When I press the button, such a waiting screen appears: gif Commented Mar 4, 2021 at 18:23
  • You can see the page is spinning - things are loading without the page changing. That means it's in-page scripts getting new data. You'll need an explicit or implicit wait before you can access the elements. Commented Mar 4, 2021 at 19:34
  • @RichEdwards I'm already using sleep(5) to wait for it to load but it doesn't change anything. Commented Mar 4, 2021 at 19:48
  • 've had a look for you - there is an iframe in the modal. see the answer below on how to identify and how to handle. Commented Mar 5, 2021 at 12:06

1 Answer 1

2

Your element is within an iframe. If you keep scrolling up in your DOM you'll see this:

enter image description here

In order to handle iframes with selenium:

  1. You need to switch to it
  2. You then can complete your action
  3. You then need to switch back to the parent frame to continue with the script:

Like this:

driver.implicitly_wait(10) # this will wait up to 10 seconds for an object to be present

#your code:
driver.find_element_by_xpath('//*[@id="buy-now-button"]').click()

#iframe switch:
iframe = driver.find_element_by_xpath("//iframe[contains(@id,'turbo-checkout-iframe')]")
driver.switch_to.frame(iframe)

#your code:
x = driver.find_elements_by_xpath("//*[@id='turbo-checkout-pyo-button']")
if len(x) > 0:
    y = driver.find_element_by_xpath("//*[@id='turbo-checkout-pyo-button']")
    y.click()

#back to the main frame to continue the script 
driver.switch_to_default_content()

You probably don't need the find_elements, and the if len parts - you can probably go straight to the click. However the above is an answer to why you cannot find your element.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.