页面操作中,点击某个链接会打开新的窗口,定位新窗口中的元素,需要跳转到新窗口操作(即使已经打开新的窗口,你的句柄和title还是前面窗口的),可以使用以下方法:
- current_window_handle
- window_handles
- switch_to.window(handle)
例子:
1. 打开百度首页,点击登录按钮,点击立即注册按钮,打开新的窗口
2. 跳转到注册窗口,在注册窗口进行操作
3. 跳回到百度首页,点击登录弹出框的关闭按钮,在百度首页进行操作
1 from selenium import webdriver
2 import time
3
4 driver = webdriver.Chrome()
5 driver.maximize_window()
6 driver.get('http://www.baidu.com')
7
8 search_window = driver.current_window_handle # 获取当前窗口句柄
9 time.sleep(3)
10 driver.find_element_by_link_text('登录').click()
11 time.sleep(3)
12 driver.find_element_by_link_text('立即注册').click()
13
14 all_window_handles = driver.window_handles # 获取当前所有打开窗口的句柄
15
16 for handle in all_window_handles:
17 if handle != search_window:
18 driver.switch_to.window(handle) # 跳转到注册窗口
19 driver.find_element_by_id('TANGRAM__PSP_4__userName').send_keys('jda')
20 driver.find_element_by_id('TANGRAM__PSP_4__phone').send_keys('13100000000')
21 driver.find_element_by_id('TANGRAM__PSP_4__password').send_keys('fda')
22 time.sleep(3)
23
24 for handle in all_window_handles:
25 if handle == search_window:
26 driver.switch_to.window(handle) # 跳转到百度首页窗口
27 driver.find_element_by_id('TANGRAM__PSP_4__closeBtn').click()
28 driver.find_element_by_id('kw').send_keys('zhangyang')
29 driver.find_element_by_id('su').click()
30 time.sleep(3)
31
32
使用js,打开新的tab页面
js1 = 'window.open("https://163.com")'
driver.execute_script(js1)
js = 'window.open("{}")'.format("http://www.baidu.com")
js = f'window.open("{"http://www.163.com"}")'
例子:循环打开三个页面,并打印handle和title
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.maximize_window()
driver.implicitly_wait(10)
urls = ['https://www.baidu.com', 'http://www.163.com', 'http://www.qq.com']
for url in urls:
js = 'window.open("{}")'.format(url)
driver.execute_script(js)
driver.switch_to.window(driver.window_handles[-1])
print(driver.window_handles)
print(driver.current_window_handle)
print(driver.title)
time.sleep(3)
driver.quit()