python selenium 定位iframe(多层框架)

来源:互联网 发布:在线sql注入漏洞检测 编辑:程序博客网 时间:2024/05/17 07:01

在 web 应用中经常会出现 iframe 嵌套的应用,假设页面上有 A、B 两个 iframe,其中 B 在 A 内,那么定位 B 中的内容则需要先到 A,然后再到 B。

iframe 中实际上是嵌入了另一个页面,而 webdriver 每次只能在一个页面识别,因此需要用 switch_to.frame 方法去获取 iframe 中嵌入的页面,对那个页面里的元素进行定位。

如果iframe里有id或者name,使用switch_to_frame()可以很方便的定位到,如

例1:

# 先找到到 ifrome1(id = f1)

driver.switch_to_frame("f1")

# 再找到其下面的 ifrome2(id =f2)

driver.switch_to_frame("f2")

# 下面就可以正常的操作元素了

driver.find_element_by_id("xx").click()

注:切到frame中之后,我们便不能继续操作主框架的元素,这时如果想操作主框架内容,则需切回主文档(最上级文档);若使用后需要再次对iframe定位需要重新从初始化的frame进行定位。

br.switch_to.default_content()

但有时会碰到iframe里没有id或者那么的情况,这就需要其他办法去定位了,如:

例2:


方法一:从顶层开始定位,相对比较费劲。

text1 = browser.find_element_by_class_name("bodybg")

text2 = text1.find_element_by_xpath("div[@class='Lean_overlay']/div[2]")

# 输入iframe里的src内容,确认已经定位到iframe

# text3 = text2.find_element_by_tag_name("iframe").get_attribute("src")

# print text3

text = text2.find_element_by_tag_name("iframe")

browser.switch_to.frame(text)

方法二:定位到上一次,然后再定位到iframe。

#找出所有class_name=qh-login的上一层元素

text1 = browser.find_elements_by_class_name("qh-login")

for text in text1:

if text.get_attribute("id") == "idname":

print text.get_attribute("class")

text2 = text.find_element_by_tag_name("iframe").get_attribute("src")

else:

text2 = str("定位失败了")

---------------------------------------------------------------------------------------------------------------------------------

有可能嵌套的不是框架,而是窗口,还有针对窗口的方法:switch_to_window 

用法与switch_to_frame 相同: 

driver.switch_to_window("windowName")

有的页面镶嵌的是frame:

用法与switch_to_frame相同:

driver.switch_to.frame("id||name")


0 0