理論上 selenuim 處理多個分頁或頁框(frame),只是在分頁的切換(switch_to)是「前景切換」不是「背景」所以,UI 上會為了處埋多個分頁(或彈出式視窗)而變的很難處理;反之,如果是同一個tab 多個 frameset 就不會很奇怪。
檢測使用者是否已「關閉作用中的分頁」,可以服用下面的範例:
from selenium.common.exceptions import NoSuchWindowException
While True:
try:
[navigate to the new frame, wait for a specific element to show up]
break
except (NoSuchWindowException, NoSuchElementException):
pass
有趣的小範例2號:
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("http://www.max-everyday.com")
driver.execute_script("window.open()")
driver.switch_to.window(driver.window_handles[1])
driver.switch_to.window(driver.window_handles[0])
driver.close()
print(driver.current_window_handle)
#selenium.common.exceptions.NoSuchWindowException: Message: no such window: target window already closed
driver.execute_script("window.open()")
#selenium.common.exceptions.NoSuchWindowException: Message: no such window: target window already closed
driver.switch_to.window(driver.window_handles[0])
driver.execute_script("window.open()")
附註,如果需要在開新視窗時指定要開啟的網址,請試這組:
from selenium import webdriver
browser = webdriver.Chrome()
browser.get("https://www.google.com")
browser.execute_script('window.open("http://www.max-everyday.com")'