【问题标题】:How to switch between different chrome browser window opened by different WebDriver using selenium in Python?python - 如何在Python中使用selenium在不同WebDriver打开的不同chrome浏览器窗口之间切换?
【发布时间】:2018-08-19 08:42:20
【问题描述】:

我搜索了这个问题,我发现了一个使用 driver.switch_to.window() 的想法,但它没有按预期工作:

from selenium import webdriver

driver1=webdriver.Chrome("D:\Python\Files\chromedriver.exe")
driver1.get('https://www.google.com')


driver2=webdriver.Chrome("D:\Python\Files\chromedriver.exe")
driver2.get('https://www.bing.com/')

driver1.switch_to.window(driver1.current_window_handle)

上面的代码会先打开一个chrome窗口去google,然后再打开另一个chrome窗口去bing,然后

driver1.switch_to.window(driver1.current_window_handle)

似乎不起作用,显示 bing 的窗口仍然显示在显示 google 的窗口顶部。 有人知道吗?我想

driver1.switch_to.window(driver1.current_window_handle)

可能有一些BUG。

【问题讨论】:

    标签: python selenium selenium-webdriver webdriver


    【解决方案1】:

    我相信您在 driver.switch_to.window() 中有不同的“窗口”概念。在 chrome 浏览器中,它的意思是“标签”。它不是另一个 chrome 浏览器或浏览器窗口,就像您在代码中尝试做的那样。

    如果 switch_to.window() 是你真正想要的,我会举例说明如何使用它:

    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
    

    【讨论】:

    • 谢谢。我误解了'switch_to_window'的意思,它会在同一个webdriver的标签之间切换。但我真正的意思是在不同的webdriver窗口之间切换,你有什么建议吗?
    【解决方案2】:

    因为您已经使用了两个 WebDriver 实例分别作为 driver1driver2 来打开 URL https://www.google.com(例如 windowA)和 https://www.bing.com/ (例如windowB) 值得一提的是函数switch_to.window() 是一个WebDriver 方法。所以,driver1只能控制windowAdriver2只能控制windowB

    Selenium 要与任何浏览窗口 交互,Selenium 需要focus。因此,要在不同的浏览窗口之间进行迭代,您可以使用 JavascriptExecutor 将焦点转移到不同的浏览窗口,如下所示:

    • Python

      driver1.execute_script("window.focus();")
      driver2.execute_script("window.focus();")
      
    • Java

      ((JavascriptExecutor) driver1).executeScript("window.focus();");
      ((JavascriptExecutor) driver2).executeScript("window.focus();");
      

    【讨论】:

      猜你喜欢
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-23
      • 2015-02-20
      • 2013-06-23
      • 1970-01-01
      • 2016-12-21
      相关资源
      最近更新 更多