打开新窗口获取元素

操作新窗口的元素时,需要先获取下新窗口的句柄,否则会导致页面元素查询不到,以百度为例:

from selenium import webdriver
from time import *
driver = webdriver.Chrome()
driver.implicitly_wait(10)
driver.get('http://www.baidu.com/')

#获取百度首页句柄
sreach_windows = driver.current_window_handle

#打开注册页面
driver.find_element_by_link_text('登录').click()
driver.find_element_by_link_text('立即注册').click()

#获取当前所有打开窗口的句柄
all_handle = driver.window_handles
print(all_handle)

sleep(10)

#打开注册句柄
for handle in all_handle:
if handle != sreach_windows:
driver.switch_to.window(handle)#实现对新窗口句柄的捕捉
driver.find_element_by_name('userName').send_keys('123')

#打开百度首页句柄
for handle in all_handle:
if handle == sreach_windows:
driver.switch_to.window(handle)#实现对新窗口句柄的捕捉
driver.find_element_by_name('wd').send_keys('456')
driver.find_element_by_id('TANGRAM__PSP_4__closeBtn').click()

driver.quit()
原文地址:https://www.cnblogs.com/xiaobinglife/p/10059173.html