Selenium Chrome浏览器窗口切换

了解更多关注微信公众号“木下学Python”吧~

 

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
import time

browser = webdriver.Chrome()
browser.set_window_size(900, 900)   # 根据桌面分辨率来定

# 打开淘宝页面
browser.get("https://www.taobao.com/")

# 获取淘宝页面的 title和handle信息
taobaoWindowHandle = browser.current_window_handle
taobaoTitle = browser.title
print(f"1. taobaoTitle = {taobaoTitle}, taobaoWindowHandle = {taobaoWindowHandle}")

# 打开路由器配置页面 http://172.16.0.1
js = 'window.open("http://172.16.0.1");'
browser.execute_script(js)
time.sleep(2)
# 如果没有switch做窗口切换的话,即使有打开新的窗口,浏览器还是会focus在原来的窗口
print(f"2. routing Configure Page had been opened, currentTitle = {browser.title}, currentHandle = {browser.current_window_handle}")

# 拿到所有的窗口
allHandles = browser.window_handles
print(f"3. allHandles = {allHandles}")

# 第一种思路:按照handle,从淘宝窗口切换到路由器配置窗口
routeWindowHandle = 0
routeTitle = 'None'
for handle in allHandles:
    if handle != browser.current_window_handle:
        browser.switch_to_window(handle)
        routeWindowHandle = browser.current_window_handle
        routeTitle = browser.title
        break
print(f"4. switch to routeWindow, routeWindowHandle = {routeWindowHandle}, routeTitle = {routeTitle}, currentHandle = {browser.current_window_handle}, currentTitle = {browser.title}")

# 第二种思路:当然还有一种方法是根据窗口的title进行切换
# 从路由器配置窗口,切换回淘宝窗口
for handle in allHandles:
    if browser.title.find("淘宝网") == -1:
        browser.switch_to_window(handle)
print(f"5. switch to taobaoWindow, taobaoWindowHandle = {taobaoWindowHandle}, taobaoTitle = {taobaoTitle}, currentHandle = {browser.current_window_handle}, currentTitle = {browser.title}")

time.sleep(30)
# 第三种思路:按照windowHandle切换,切换到taobao窗口
browser.switch_to_window(taobaoWindowHandle)
print(f"6. switch back to taobao window, currentHandle = {browser.current_window_handle}, taobaoWindowHandle = {taobaoWindowHandle}, routeWindowHandle = {routeWindowHandle}")

time.sleep(10)
browser.quit()

 

获得所有窗口句柄

all_handles = driver.window_handles

 

切换指定窗口

# 打开多个标签,会默认从左到右。索引从 0 开始,记录进 window_handles

driver.switch_to.window(driver.window_handles[0])

如果用 close 关闭了一个窗口,还需要继续在浏览器操作的话,需要使用它切换一个存在的窗口

 

 

 

你可能感兴趣的:(Selenium)