如何使用 Python Selenium 切换不同的浏览器选项卡?
我们可以使用 Python 中的 Selenium webdriver 使用 switch_to.window 方法切换不同的浏览器选项卡。默认情况下,webdriver 可以访问父窗口。
一旦打开了另一个浏览器选项卡,switch_to.window 将有助于将 webdriver 焦点切换到该选项卡。我们要切换到的浏览器窗口的窗口句柄作为参数传递给该方法。
window_handles 方法包含已打开浏览器的所有窗口句柄 id 的列表。current_window_handle 方法用于保存处于焦点状态的浏览器窗口的窗口句柄 id。
语法
p = driver.current_window_handle parent = driver.window_handles[0] chld = driver.window_handles[1] driver.switch_to.window(chld)
让我们尝试访问以下浏览器选项卡 −

示例
from selenium import webdriver
#set chromodriver.exe path
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
driver.implicitly_wait(0.5)
#launch URL
driver.get("https://the-internet.herokuapp.com/windows")
#identify element
l = driver.find_element_by_link_text("Click Here")
l.click()
#obtain window handle of browser in focus
p = driver.current_window_handle
#obtain parent window handle
parent = driver.window_handles[0]
#obtain browser tab window
chld = driver.window_handles[1]
#switch to browser tab
driver.switch_to.window(chld)
print("Page title for browser tab:")
print(driver.title)
#close browser tab window
driver.close()
#switch to parent window
driver.switch_to.window(parent)
print("Page title for parent window:")
print(driver.title)
#close browser parent window
driver.close()输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP