如何使用Selenium和Python在iframe之间切换? [英] How to switch between iframes using Selenium and Python?
问题描述
我正在尝试编写脚本以在Shopify网站上结帐,但我能够找到卡号的iframe,但无法找到卡上名称的iframe(第二个iframe).有什么办法可以为该iframe输入值?
I'm trying to make a script to checkout on a Shopify site and I was able to find the iframe for the card number, but was not able to find the iframe for the name on the card (2nd iframe). Is there any way to enter in a value for that 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
推荐答案
卡号和名称字段位于不同的< iframe>
因此您必须:
The card number and name fields are in different <iframe>
so you have to:
-
引发 WebDriverWait 所需的框架可用,并切换到 卡号字段.
切换到默认内容
引发 WebDriverWait 以使所需的框架可用,并在 name 字段中切换到该框架.
Induce WebDriverWait for the desired frame to be available and switch to it for the name field.
You can use either of the following xpath based Locator Strategies:
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')]")))
注意:您必须添加以下导入:
Note : You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
您可以在以下位置找到一些相关的讨论:
You can find a couple of relevant discussions in:
这篇关于如何使用Selenium和Python在iframe之间切换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!