场景
在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
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body><div ><h3>frame</h3><iframe id="f1" src="inner.html" width="900" height="600"></iframe></div></body></html> |
inner.html
|
1
2
3
4
5
6
7
8
9
10
11
12
|
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body><h3>inner</h3><iframe id="f2" src="http://www.baidu.com" width="800" height="400"></iframe></body></html> |
主程序
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
#!/usr/bin/env python# -*- codinfg:utf-8 -*-'''@author: Jeff LEE@file: iframe.py@time: 2020-01-08 17:23@desc:'''from selenium import webdriverimport time,osdriver = 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() |