How to switch between different chrome browser window opened by different WebDriver using selenium in Python?

前端 未结 2 549
日久生厌
日久生厌 2020-12-22 03:05

I searched for this question,and I found an idea using driver.switch_to.window(),but it didn\'t work as expect:

from selenium import webdriver

driver1=webdr         


        
相关标签:
2条回答
  • 2020-12-22 03:08

    I believe you have a different concept of "window" in driver.switch_to.window(). In chrome browser, it means "tab". It's not another chrome browser or browser window like what are you trying to do in your code.

    If switch_to.window() what you really want, I'll give an example how to use it:

    driver=webdriver.Chrome("D:\Python\Files\chromedriver.exe")
    driver.get('https://www.google.com')
    # open a new tab with js
    driver.execute_script("window.open('https://www.bing.com')")
    driver.switch_to.window(driver.window_handles[-1])
    # now your driver is pointed to the "tab" you just opened
    
    0 讨论(0)
  • 2020-12-22 03:11

    As you have used two WebDriver instances as driver1 and driver2 respectively to openthe urls https://www.google.com (e.g. windowA) and https://www.bing.com/ (e.g. windowB) it is worth to mention that the function switch_to.window() is a WebDriver method. So, driver1 can control only windowA and driver2 can control only windowB.

    For Selenium to interact with any of the Browsing Window, Selenium needs focus. So to iterate among the different Browsing Windows you can shift the focus to the different Browsing Window using JavascriptExecutor as follows :

    ((JavascriptExecutor) driver1).executeScript("window.focus();");
    ((JavascriptExecutor) driver2).executeScript("window.focus();");
    
    0 讨论(0)
提交回复
热议问题