pythonselenium-webdriver

Opening a new pop-up screen, filling in form


I've created a py file. In this script:

After selecting the correct time an new pop-up screen is opened. In this screen I have to fill in some fields. But my py file does not recognize the new pop up screen. The URL of the new pop-up screen is different everytime (based on date etc).

Can you help me what I have to do in the PY script, so Python does know that he has to perform action in the new pop-up screen??

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

# Initialize the WebDriver
driver = webdriver.Chrome()  

# Open de website
driver.get("https://bent.baanreserveren.nl")  

# Tijd om scherm goed te stellen
time.sleep(1)

# Vul Gebruikersnaam in
driver.find_element(By.NAME, "username").send_keys("username")

# Vul Wachtwoord in
driver.find_element(By.NAME, "password").send_keys("password")

# Klik op Inloggen
driver.find_element(By.CSS_SELECTOR, ".form-submit3 > .button3").click()

# Juiste dag (3x klikken)< let op wijzigen nadat het correct is
for _ in range(2):
    element = driver.find_element(By.CSS_SELECTOR, ".matrix-date-nav:nth-child(3)")
    element.click()
    time.sleep(1) 

# Selecteer Padel Buiten uit Dropdown lijst
dropdown_element = driver.find_element(By.ID, "matrix-sport")
dropdown_element.click()
element = dropdown_element.find_element(By.XPATH, "//option[. = 'Padel Buiten']")
element.click()
time.sleep(1)

# Selecteer baan 3, tijdstip 21:00 uur    
element = driver.find_element(By.CSS_SELECTOR, "tr:nth-child(57) > .r-4436 > .slot-period")
element.click()

# FROM THIS POINT HE IS OPENING AN NEW POP-UP SCREEN AND I HAVE GO FURTHER ON THE NEW SCREEN

# Sluit de website
driver.quit()

Hoping to find the solution


Solution

  • I think you're looking for the switch_to.window() function in selenium.

    # before you click to open the new window, get the original window's handle
    original_window = driver.current_window_handle
    
    ...
    element.click()
    
    # wait for second window to be ready
    wait.until(EC.number_of_windows_to_be(2))
    
    # loop through handles until we find the new window handle (by comparing with the original)
    for window_handle in driver.window_handles:
      if window_handle != original_window:
        driver.switch_to.window(window_handle)
        break
    

    Your driver is now managing the new window. When you're done, switch back to the original handle, original_window.