简体   繁体   English

Python selenium 在模态中找不到元素

[英]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']"}

截屏

Your element is within an iframe.您的元素位于 iframe 中。 If you keep scrolling up in your DOM you'll see this:如果您继续在 DOM 中向上滚动,您会看到:

在此处输入图像描述

In order to handle iframes with selenium:为了使用 selenium 处理 iframe:

  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.您可能不需要find_elementsif len部分 - 您可以直接点击 go 。 However the above is an answer to why you cannot find your element.然而,以上是为什么你找不到你的元素的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM