python - 如何使用 Selenium 和 Python 在 iF​​rame 中定位元素

标签 python selenium xpath iframe webdriverwait

这是 ifram 源代码:

<iframe sandbox="allow-scripts allow-same-origin" class="credit-card-iframe mt1 u-full-width prl2-sm" src="https://paymentcc.nike.com/services/default?id=3f42d8c5-74ee-4d08-95aa-bb6ea4949f9f&amp;ctx=checkout&amp;language=en-GB&amp;maskerEnabled=true" frameborder="0" scrolling="no" xpath="1"></iframe>

这就是我想要的元素;

<input maxlength="20" class="mod-ncss-input ncss-input pt2-sm pr4-sm pb2-sm pl4-sm" id="creditCardNumber" onautocomplete="off" value="" type="tel" tabindex="0" data-shortname="cc">

这是我的代码:

browser.switch_to.frame(browser.find_element_by_xpath("//iframe[@class='credit-card-iframe mt1 u-full-width prl2-sm']"))
browser.implicitly_wait(10)
card = browser.find_element_by_xpath("//input[@id='creditCardNumber']")
card.send_keys("35663565444")

这是错误:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//input[@id='creditCardNumber']"}

此外,如果我必须在页面上滚动才能看到某些内容,该元素仍然可以被拾取,谢谢。

最佳答案

因为所需的元素在 <iframe> 中所以调用click()在你必须的元素上:

  • 诱导 WebDriverWait 所需的框架可用并切换到它
  • 诱导 WebDriverWait 使所需的元素可点击
  • 您可以使用以下 Locator Strategies::

    • 使用 XPATH :

      WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@sandbox='allow-scripts allow-same-origin' and contains(@class, 'credit-card-iframe')]")))
      WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//input[@id='creditCardNumber' and @data-shortname='cc']"))).send_keys("35663565444")
      
    • 注意:您必须添加以下导入:

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

引用

您可以在以下位置找到相关讨论:

关于python - 如何使用 Selenium 和 Python 在 iF​​rame 中定位元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60218231/

相关文章:

python - 文件未找到错误: [Errno 2] No such file or directory: 'python' : 'python' while running a python script

python GIL : concurrent C++ embed

java - org.openqa.selenium.SessionNotCreatedException : Unable to find a matching set of capabilities

xpath - 如何在 xpath 中选择替代子路径

python django 休息框架。如何以某种特定格式序列化外键 UUID?

python - Pyspark - 将数据帧写入 2 个不同的 csv 文件

selenium - 如何杀死多个 geckodriver.exe 进程?

java - Selenium RemoteWebDriver - 如果找不到元素则执行某些操作

java - Xpath 的 FindElement 不适用于 "add New"按钮

SQL:如何获取 XML 数据类型中的属性值?