Python. Selenium. How to wait for new window opens?

✔ Recommended Answer

As Surya mentioned, WebDriverWait would be the way to wait for a change. You could have a context manager like this that only implements the wait logic and then use it for any kind of operation you care about:

@contextmanagerdef wait_for_new_window(driver, timeout=10):    handles_before = driver.window_handles    yield    WebDriverWait(driver, timeout).until(        lambda driver: len(handles_before) != len(driver.window_handles))

Here's a full working example:

from selenium import webdriverfrom selenium.webdriver.support.ui import WebDriverWaitfrom contextlib import contextmanager@contextmanagerdef wait_for_new_window(driver, timeout=10):    handles_before = driver.window_handles    yield    WebDriverWait(driver, timeout).until(        lambda driver: len(handles_before) != len(driver.window_handles))driver = webdriver.Chrome()driver.get("http://www.google.com")with wait_for_new_window(driver):    driver.execute_script("""    window.open("http://www.google.com", "_blank");    """)with wait_for_new_window(driver, 2):    pass # This will obviously hit the timeout.driver.quit()

Source: stackoverflow.com

Answered By: Louis

Comments

Most Popular

Remove Unicode Zero Width Space PHP

PhpStorm, return value is expected to be 'A', 'object' returned

Laravel file upload returns forbidden 403, file permission is 700 not 755