[PYTHON] Wait for another window to open in Selenium

problem

I'm working with a web page in Selenium. Clicking on one link opens another window and I want to transfer control to that window.

from selenium import webdriver

driver = webdriver.Chrome()
driver.get('http://www.tagindex.com/html_tag/link/a_target.html')
driver.find_element_by_css_selector('[href="target_example.html"]').click()

driver.switch_to.window(driver.window_handles[1])

However, this code may fail with ʻIndexError without driver.window_handles [1] `existing: sob:

solution

By using WebDriverWait.until () until another window opens You can wait.

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait

driver = webdriver.Chrome()
driver.get('http://www.tagindex.com/html_tag/link/a_target.html')
driver.find_element_by_css_selector('[href="target_example.html"]').click()

WebDriverWait(driver, 3).until(lambda d: len(d.window_handles) > 1)
driver.switch_to.window(driver.window_handles[1])

This ensures that control can be transferred to another window: blush:

Recommended Posts

Wait for another window to open in Selenium
Seeking a unified way to wait and get for state changes in Selenium for Python elements
Selenium and python to open google
selenium: wait for element with AND / OR
Wait for Aurora Serverless to wake up
I want to create a window in Python
Log in to Yahoo Business with Selenium Python
Try to calculate RPN in Python (for beginners)
Unable to open file for writing About sudo
[For beginners] Introduction to vectorization in machine learning
Tool to make mask image for ETC in Python
[For beginners] How to use say command in python!
Key input that does not wait for key input in Python
How to run python in virtual space (for MacOS)
Mac application for double-clicking to open Jupyter Notebook (* .ipynb)
I was addicted to scraping with Selenium (+ Python) in 2020
How to download files from Selenium in Python in Chrome
Convenient to use matplotlib subplots in a for statement
When you want to plt.save in a for statement