如何使用 Selenium 和 Python 在 iframe 之间切换?

How to switch between iframes using Selenium and Python?

我正在尝试制作一个脚本以在 Shopify 网站上结账,我能够找到卡号的 iframe,但找不到卡上名称的 iframe(第二个 iframe) .有什么方法可以为该 iframe 输入值吗?

driver.switch_to.frame(driver.find_element_by_tag_name("iframe"))
driver.find_element_by_xpath('//input[@autocomplete="cc-number"]').send_keys("1234")
driver.find_element_by_xpath('//div[@data-card-field-placeholder="Name on card"]').click()
driver.switch_to.frame(driver.find_element_by_tag_name("iframe"))
driver.find_element_by_xpath('//input[@autocomplete="cc-name"]').send_keys("First Last")

我试过了

driver.find_element_by_xpath('//input[@autocomplete="cc-name"]').send_keys("First Last")

它让我无法定位元素

参考图片:https://imgur.com/a/cx7tByw

像对任何其他元素一样使用唯一定位符

切换到框架的语法是

   driver.switch_to.frame(WebElement)

所以你不需要只使用标签名称,你可以像任何元素一样使用 xpath、Id、css 等

我们通常使用标签,因为大多数情况下只有一个 iframe。如果您有多个 iframe,请使用特定 iframe

的任何其他属性(如 I'd,class 等)像其他元素一样唯一地找到每个 iframe

driver.switch_to.frame(driver.find_element_by_xpath('//iframe[@id="card-fields-name-fpsn1ey65to00000"]'))

我建议使用父标签,因为它有一个更易于识别的 div 标签,可以 xpathed to.This 这样你就可以在找到输入标签之前转到你想要的 iframe将密钥发送至。

driver.switch_to.frame(driver.find_element_by_xpath("div[@data-card-fields='number']/iframe"))

卡号姓名字段在不同的<iframe>所以你必须:

  • 诱导WebDriverWait所需的帧可用并切换到卡号 字段。

  • 切换到默认内容

  • 诱导 WebDriverWait 以获得所需的 框架并切换到 以获得 name场.

  • 您可以使用以下任一项 based :

    WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@class='card-fields-iframe' and starts-with(@id, 'card-fields-number')]")))
    # perform other operations
    driver.switch_to.default_content()
    WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@class='card-fields-iframe' and starts-with(@id, 'card-fields-name')]")))
    
  • 注意:您必须添加以下导入:

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

参考

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

  • Switch to an iframe through Selenium and python