Python3 Selenium多窗口切换

2023-05-12,,

Python3 Selenium多窗口切换

以腾讯网(http://www.qq.com/)为例,打开腾讯网,点击新闻,打开腾讯新闻,点击新闻中第一个新闻链接。

在WebDriver中封装了获取当前窗口句柄方法和获取所有窗口句柄的方法以及切换指定句柄窗口的方法;
(句柄:英文handle,窗口的唯一识别码)
方法:
1). driver.current_window_handle --> 获取当前窗口句柄
2). driver.window_handles --> 获取所有窗口句柄
3). driver.switch_to.window(handle) --> 切换指定句柄窗口


import time
from selenium import webdriver # 创建Chrome浏览器驱动对象
driver = webdriver.Chrome()
# 加载腾讯网页面
driver.get('http://www.qq.com/')
# 窗口最大化
driver.maximize_window() time.sleep(3)
# 切换窗口
"""
1. 获取腾讯首页当前窗口句柄
2. 点击腾讯首页页面中新闻中心链接
3. 获取所有窗口句柄
4. 遍历判断窗口句柄并切换到新闻中心_腾讯网
5. 点击新闻中心_腾讯网页面第一个新闻链接,打开新闻详情页
"""
current_handle = driver.current_window_handle
print('当前窗口句柄为:', current_handle) # 定位-点击腾讯首页页面中新闻中心_腾讯网链接
driver.find_element_by_xpath('/html/body/div[1]/div[2]/div/ul/li[1]/a').click() # 获取所有窗口句柄
handles = driver.window_handles
print('所有窗口句柄为:', handles)
for handle in handles:
print('遍历窗口为:', handle)
if handle != current_handle:
# 切换到新闻中心_腾讯网
driver.switch_to.window(handle)
# 点击新闻中心第一个新闻链接,打开新闻详情页
driver.find_element_by_xpath('//*[@id="subHot"]/h2/a').click() time.sleep(3) # 关闭Chrome浏览器
driver.quit()

 

这是常用的方法,以下是另外一种方法,简单

import time
from selenium import webdriver # 创建Chrome浏览器驱动对象
driver = webdriver.Chrome()
# 加载腾讯网页面
driver.get('http://www.qq.com/')
# 窗口最大化
driver.maximize_window() time.sleep(3)
# 切换窗口
"""
1. 获取腾讯首页当前窗口句柄
2. 点击腾讯首页页面中新闻中心链接
3. 获取所有窗口句柄
4. 遍历判断窗口句柄并切换到新闻中心_腾讯网
5. 点击新闻中心_腾讯网页面第一个新闻链接,打开新闻详情页
"""
current_handle = driver.current_window_handle
print('当前窗口句柄为:', current_handle) # 定位-点击腾讯首页页面中新闻中心_腾讯网链接
driver.find_element_by_xpath('/html/body/div[1]/div[2]/div/ul/li[1]/a').click() # 获取所有窗口句柄
handles = driver.window_handles
print('所有窗口句柄为:', handles)
driver.switch_to.window(handles[-1])
# 点击新闻中心第一个新闻链接,打开新闻详情页
driver.find_element_by_xpath('//*[@id="subHot"]/h2/a').click() time.sleep(3) # 关闭Chrome浏览器
driver.quit()

  

Python3 Selenium多窗口切换的相关教程结束。

《Python3 Selenium多窗口切换.doc》

下载本文的Word格式文档,以方便收藏与打印。