selenium 多窗口切換


#coding=utf-8
#多窗口:如點了某個鏈接后,會再多打開一個新窗口,即新標簽頁
from selenium import webdriver
driver = webdriver.Firefox()
driver.implicitly_wait(10)
driver.get("http://www.baidu.com")

#獲得當前窗口句柄
search_windows = driver.current_window_handle
driver.find_element_by_link_text('登錄').click()
driver.find_element_by_link_text('立即注冊').click()
#獲得當前打開所有窗口的句柄
all_handles = driver.window_handles

#進入注冊窗口
for handle in all_handles:
if handle !=search_windows:
#如果當前窗口不是百度首頁的句柄,則切換到注冊句柄
driver.switch_to_window(handle)
print ('now register window!')
zhuce_windows = driver.current_window_handle
driver.find_element_by_name("account").send_keys('username')
driver.find_element_by_name("password").send_keys('password')


#返回搜索窗口
for handle in all_handles:
if handle == search_windows:
driver.switch_to_window(handle)
print ("now resarch window")

#如果當前打開的不止兩個窗口,則需要在每個窗口打開的時候,獲取一次句柄,要切換到任何一個窗口,只需要再switch一下
#如這個是獲取注冊頁的句框zhuce_windws = driver.current_window_handle
#切換時只要driver.switch_to_window(zhuce_windows) ,或者使用for +and進行循環

'''
for handle in all_handles:
if handle != search_windows and handle !=zhuce_windows
driver.switch_to_window(handle)
print ("now is the thirds window")
'''


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM