【问题标题】:Locating a button by xpath or id通过 xpath 或 id 定位按钮
【发布时间】:2021-03-04 12:08:34
【问题描述】:

网站来源是:

<iframe id="fast-checkout-iframe">
<div  class="celwidget" >
        <span class="a" data-action="place-order">
           <span id="checkout-place-order-button" >
             <span class="a-button-inner">
               <input id="fast-checkout-button" type="submit" value="Place your order" >
                 <span id="fast-checkout-place-order-button-announce" >Place your order
</span></span></span></span></div>
</iframe>

我正在尝试点击切换到 iframe 并点击按钮。

self.driver.switch_to.frame(self.driver.find_element_by_tag_name("iframe"))
self.driver.find_element_by_id("fast-checkout-button").click()

但我明白了:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="fast-checkout-button"]"}

What should I do? Thanks!

【问题讨论】:

  • 你的元素必须在iframe??如果您发布的元素上方有任何父元素,例如iframe,请检查 DOM 树?如果不尝试显式等待。
  • 是的。我在上面看到一个 iframe 标记...我该怎么办?
  • 页面上是否只有 1 个 iframe?我相信你可以 swith_to 使用 id

标签: python-3.x selenium selenium-webdriver selenium-chromedriver


【解决方案1】:

使用WebDriverWait() 并等待element_to_be_clickable() 并遵循xpath。

wait = WebDriverWait(driver, 20)
buttons = wait.until(EC.element_to_be_clickable((By.XPATH, "//input[@id='fast-checkout-button']")))
buttons.click()

您需要导入以下库

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

如果您仍然收到超时错误,请检查它是否在iframe


更新

你需要先切换到iframe才能访问iframe中的元素。

#Switch to frame
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.ID, "fast-checkout-iframe")))  
#Click on the button
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, //input[@id='fast-checkout-button']"))).click()

#To switch back to the main
driver.switch_to.default_content()

【讨论】:

  • 我看到了 iframe ..我忘了检查这个。知道我能做什么吗?使用你的解决方案我得到超时错误..
  • @MMarie:你需要先切换 iframe 吗?可以请发布 iframe 的 html 吗?
  • 我改变了最初的帖子:)
【解决方案2】:

正如@KunduK 所提到的,最好等待您的元素。此外,仅查看源代码,我认为您应该尝试单击input 元素,而不是span。所以请改用 id fast-checkout-button

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-06
    • 1970-01-01
    • 1970-01-01
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-14
    相关资源
    最近更新 更多