如何使用 Selenium WebDriver for python 在浏览器上打开新窗口?
我们可以用 Selenium webdriver 在浏览器中打开一个新窗口。有多种方法可以实现此目的。Selenium 可以使用 execute_script() 方法在 Javascript 中执行命令,这是一种打开新窗口的方法之一。然后,我们将使用 switch_to.window() 方法来一次将焦点转移到特定窗口。
语法 −
driver.execute_script("window.open('');")
示例
使用 execute_script() 方法的代码实现。
from selenium import webdriver urlA = "https://tutorialspoint.com/about/about_careers.htm" urlB = "https://tutorialspoint.com/questions/index.php" driver = webdriver.Chrome (executable_path="C:\chromedriver.exe") # maximize with maximize_window() driver.maximize_window() driver.get(urlA) print("Page Title of urlA : " + driver.title) # open new window with execute_script() driver.execute_script("window.open('');") # switch to new window with switch_to.window() driver.switch_to.window(driver.window_handles[1]) driver.get(urlB) print("Page Title of urlB : " + driver.title) # close window in focus driver.close() # switch back to old window with switch_to.window() driver.switch_to.window(driver.window_handles[0]) print("Current Title: " + driver.title) driver.close()
输出
我们还可以通过同时调用两个驱动会话在新窗口中打开浏览器。
示例
代码实现。
from selenium import webdriver urlA = "https://tutorialspoint.com/about/about_careers.htm" urlB = "https://tutorialspoint.com/questions/index.php" driver = webdriver.Chrome (executable_path="C:\chromedriver.exe") # opening another driver session s_driver = webdriver.Chrome (executable_path="C:\chromedriver.exe") # maximize with maximize_window() driver.maximize_window() s_driver.maximize_window() driver.get(urlA) s_driver.get(urlB) print(driver.title) print(s_driver.title) driver.quit()
输出
广告