![](/img/trans.png)
[英]Python Selenium with Chrome. How to switch between different tabs
[英]How to switch between different chrome browser window opened by different WebDriver using selenium in Python?
我搜索了這個問題,並使用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)
可能有一些錯誤。
正如你已經使用了兩個實例的webdriver作為驅動1和分別驅動2至openthe網址https://www.google.com (如窗口A)和https://www.bing.com/ (如窗口B)值得一提的是, switch_to.window()
函數是一個WebDriver方法。 因此, 驅動1只能控制窗口A和驅動2只能控制窗口B。
為了使Selenium與任何瀏覽窗口進行交互, Selenium需要重點關注 。 因此,不同的瀏覽窗你們中間迭代可以將重點轉移到使用JavascriptExecutor如下不同的瀏覽窗口 :
((JavascriptExecutor) driver1).executeScript("window.focus();");
((JavascriptExecutor) driver2).executeScript("window.focus();");
我相信您在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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.