场景
在web 应用中经常会出现frame 嵌套的应用,假设页面上有A、B 两个frame,其中B 在A 内,那么定位B 中的内容则需要先到A,然后再到B。
switch_to_frame 方法可以把当前定位的主体切换了frame 里。怎么理解这句话呢?我们可以从frame的实质去理解。frame 中实际上是嵌入了另一个页面,而webdriver 每次只能在一个页面识别,因此才需要用switch_to.frame 方法去获取frame 中嵌入的页面,对那个页面里的元素进行定位。
下面的代码中frame.html 里有个id 为f1 的frame,而f1 中又嵌入了id 为f2 的frame,该frame 加载了百度的首页。
代码
iframe.html
Titleframe
inner.html
Titleinner
主程序
#!/usr/bin/env python
# -*- codinfg:utf-8 -*-
'''
@author: Jeff LEE
@file: iframe.py
@time: 2018-09-21 17:23
@desc:
'''
from selenium import webdriver
import time,os
driver = webdriver.Firefox()
file_path ='file:///' + os.path.abspath('iframe.html')
driver.get(file_path)
driver.implicitly_wait(30)
#先找到到ifrome1(id = f1)
driver.switch_to_frame("f1")
#再找到其下面的ifrome2(id =f2)
driver.switch_to_frame("f2")
driver.find_element_by_id("kw").send_keys("uniquefu")
driver.find_element_by_id("su").click()
time.sleep(2)
driver.quit()