场景
有时候我们在测试一个web 应用时会出现多个浏览器窗口的情况,在selenium1.0 中这个问题比较难处理。webdriver 提供了相关相方法可以很轻松的在多个窗口之间切换并操作不同窗口上的元素
代码
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
#!/usr/bin/env python # -*- codinfg:utf-8 -*- ''' @author: Jeff LEE @file: 多窗口处理.py @time: 2019-12-04 10:57 @desc: ''' from selenium import webdriver import time driver = webdriver.Firefox() driver.get( 'https://www.baidu.com/' ) driver.find_element_by_id( "kw" ).clear() driver.find_element_by_id( "kw" ).send_keys( "uniquefu" ) driver.find_element_by_id( "su" ).click() time.sleep( 5 ) #获得当前窗口 nowhandle = driver.current_window_handle # driver.find_element_by_xpath(".//*[@id='2']/h3/a").click() driver.find_element_by_xpath( ".//div[@id='2']/h3/a" ).click() time.sleep( 10 ) #获取所有窗口 allhandles = driver.window_handles time.sleep( 5 ) #循环判断窗口是否为当前窗口 for handle in allhandles: if handle ! = nowhandle: driver.switch_to_window(handle) print (driver.title) time.sleep( 5 ) #切换到窗口接操作元素 driver.switch_to_window(nowhandle) print (driver.title) time.sleep( 5 ) driver.find_element_by_id( "kw" ).clear() driver.find_element_by_id( "kw" ).send_keys( "selenium" ) driver.find_element_by_id( "su" ).click() time.sleep( 5 ) if driver.title.startswith( 'selenium' ): print ( '窗口切换及元素操作成功' ) else : print ( '窗口切换及元素操作失败' ) driver.quit() |
运行结果:
1
2
|
uniquefu_百度搜索 窗口切换及元素操作成功 |