NoneS
NoneS

Reputation: 19

Python selenium can't find element in modal

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

Upvotes: 1

Views: 1999

Answers (1)

RichEdwards
RichEdwards

Reputation: 3753

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.

Upvotes: 2

Related Questions