I am using selenium to click through a website and automate a download, I am currently stumped on how to get selenium to switch to the pop-up window that is created when the download button is selected. In short, I want to interact with a pop-up window but am not familiar with the functions/syntax or process in doing this. Thanks!
Will update if I find a solution!
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service as ChromeService
import time
# Path to Chrome executable (replace if necessary)
chrome = path
url = url
# Initialize WebDriver using ChromeDriverManager (recommended)
driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))
# Open the desired URL
driver.get(url)
# Maximize the browser window
driver.maximize_window()
# Inform user to stop with CTRL+C
print("Press CTRL+C to stop program. Close Chrome Browser and stop Chrome Processes in Task Manager")
# Define elements in Base Window
iframe = '//*[@id="viz"]/iframe'
xpath1 = '/html/body/div[2]/div[2]/div[1]/div[2]/div[2]/div[5]/button'
xpath2 = '/html/body/div[6]/div/div/div/div[2]/div'
xpath3 = ''
# Define elements in Pop-Up Window
# Infinite loop checking for element (potentially inefficient)
try:
# Switch to the iframe containing the element
# Wait for the iframe to be present
iframe = WebDriverWait(driver, 15).until(
EC.presence_of_element_located((By.XPATH, iframe))
)
# Switch to the iframe containing the element
driver.switch_to.frame(iframe)
# Explicitly wait for the element within the iframe
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, xpath1))
)
# Click the element
element.click()
# Explicitly wait for the element within the iframe
element2 = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, xpath2))
)
# Click the element
element2.click()
# Move back from iframe to parent HTML
driver.switch_to.default_content()
except TimeoutException:
# Handle timeout gracefully, e.g., log a message or retry
print("Element not found. Retrying...")
time.sleep(10) # Adjust retry wait time as needed
# Move back from iframe to parent HTML
driver.switch_to.default_content()
It was lengthy, but I was able to find a solution and am now able to interact with the pop-up window. I also should note that the pop-up windows url is dynamic: