Python 3.5 - Selenium - How To Handle A New Window And Wait Until It Is Fully Loaded?
I am doing browser automation and I am blocked at a certain point: at a moment, I ask the browser to click on a button, which in turn open up a new window. But sometimes the Intern
Solution 1:
You can try to use following code to wait until new window appears:
WebDriverWait(driver, 20).until(EC.number_of_windows_to_be(2))
Your code should looks like
Button.click()
WebDriverWait(driver, 20).until(EC.number_of_windows_to_be(2))
newWindow = driver.window_handles
newNewWindow = newWindow[1]
driver.switch_to.window(newNewWindow)
Considering @JimEvans comment, try below:
current= driver.window_handles[0]
Button.click()
WebDriverWait(driver, 20).until(EC.number_of_windows_to_be(2))
newWindow = [windowforwindowin driver.window_handles if window!=current][0]
driver.switch_to.window(newWindow)
Solution 2:
What I'm using:
windows = set(driver.window_handles)
driver.execute_script("window.open()")
WebDriverWait(driver, 20).until(EC.new_window_is_opened(windows))
hwnd = list(set(driver.window_handles) - windows)[0]
You can create a function or a context manager like this answer for it if you find it necessary, but for essentially 3 lines (not counting the one that actually opens the window, which may be very different for each case), I prefer to just copy-paste.
To be thorough, here's a feature-enriched alternative:
@contextmanagerdefwait_for_new_window(driver, timeout=10, switch=True):
"""Waits for a new window to open
Parameters:
driver: WebDriver.
Selenium WebDriver object.
timeout: int
Maximum waiting time
switch: bool
If `True` (default), switches to the window.
Exemplo:
>>> with wait_for_new_window(driver) as hwnds:
... driver.execute_script("window.open()");
... print("Window opened:", hwnds[0])
"""
windows = set(driver.window_handles)
handle = []
yield handle
WebDriverWait(driver, timeout).until(EC.new_window_is_opened(windows))
hwnds = list(set(driver.window_handles) - windows)
handle.extend(hwnds)
if switch:
driver.switch_to.window(hwnds[0])
Solution 3:
The exact answer for waiting a NEW window to be fully loaded is:
using url_changes
from expected_conditions
with the old URL parameter as "about:blank" :
WebDriverWait(Driver, 15).until(EC.url_changes("about:blank"))
A sample code might look like:
...
# Wait till a new window opened (2nd window in this example)
WebDriverWait(Driver, 15).until(EC.number_of_windows_to_be(2))
# Switch to second window
window_after = Driver.window_handles[1]
Driver.switch_to.window(window_after)
# Wait till **new window fully loaded**:
WebDriverWait(Driver, 15).until(EC.url_changes("about:blank"))
...
Post a Comment for "Python 3.5 - Selenium - How To Handle A New Window And Wait Until It Is Fully Loaded?"