多个 iframe 标签 Selenium webdriver [英] Multiple iframe tags Selenium webdriver

查看:20
本文介绍了多个 iframe 标签 Selenium webdriver的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 selenium 将信用卡信息发送到站点,并且每个元素都包含在 HTML 中的单独 iframe 标记中.例如,输入信用卡号的框包含在第一个 iframe 标签中,持卡人姓名包含在第二个 iframe 中,依此类推.我能够访问第一个 iframe 标签,并将信用卡号发送到框中,但是我无法找到持卡人姓名 iframe 标签,因此无法发送输入持卡人姓名的密钥.我想知道是否有一种方法可以使用 webdriver 专门搜索第二个(或第一个元素以外的任意数字)iframe 标记.

I am trying to use selenium to send credit card info onto a site, and each element is contained in a separate iframe tag in the HTML. For example, the box to enter a credit card number is contained in the first iframe tag, and the card holder name is contained in the second iframe, and so on, and so forth. I am able to access the first iframe tag, and send the credit card number into the box, however I an unable to locate the cardholder name iframe tag, and thus cannot send the keys to enter a cardholder name. I'm wondering if there is a way to specifically search for the second (or an arbitrary number other than the first element) iframe tag with webdriver.

这是我使用的代码:

driver.switch_to.frame(driver.find_element_by_tag_name("iframe"))
cc = driver.find_element_by_id("number")
cc.send_keys(credit_card_number)

这正确地找到了包含输入卡号字段的第一个 iframe 标记,并发送了相应的密钥

This correctly found the first iframe tag which contains the field to enter a card number, and sent the appropriate keys

driver.switch_to.frame(driver.find_element_by_tag_name("iframe"))
driver.find_element_by_id("name").send_keys(cc_name)

这导致了以下错误:消息:没有这样的元素:无法定位元素:{"method":"tag name","selector":"iframe"}

This resulted in the following error: Message: no such element: Unable to locate element:{"method":"tag name","selector":"iframe"}

推荐答案

您已正确找到第一个 iframe 标签,其中包含用于输入卡片的信用卡号字段编号并发送相应的密钥.当您想将适当的密钥发送到 持卡人姓名 字段时,您需要先进入相关的框架.所以你必须切换回立即的 parent_frame(),它包含 iframe 标签,即 first iframesecond iframe 然后尝试切换到第二个 iframe 以定位 持卡人姓名 字段,如下所示:

You have correctly found the first iframe tag which contains the credit card number field to enter the card number and sent the appropriate keys. Moving forward when you want to sent the appropriate keys to the card holder name field you need to be on the relevant frame first. So you have to switch back to the immedediate parent_frame() which contains both the iframe tags i.e. first iframe and second iframe and next try to switch to the second iframe to locate the card holder name field as follows :

# as there are multiple frames so find_element_by_tag_name("iframe") will not suffice and have to use unique css/xpath
driver.switch_to.frame(driver.find_element_by_xpath("xpath_of_iframe1"))
cc = driver.find_element_by_id("number")
cc.send_keys(credit_card_number)
driver.switch_to.default_content() #incase iframe1 and iframe2 are immediate child of the Top Level Content
driver.switch_to.frame(driver.find_element_by_xpath("xpath_of_iframe2"))
cc = driver.find_element_by_id("name")
cc.send_keys(cc_name)

注意:根据最佳实践,您不应该通过 find_element_by_tag_name("iframe") 多个