Switch_to API
The switch_to method handles alert dialogs, frame switching, and browser window navigation.
Working with JavaScript Alert Dialogs
JavaScript creates three types of dialogs in HTML pages: alert, confirm, and prompt. Selenium provides methods to interact with these dialogs.
alert = driver.switch_to.alert # Switch focus to the active dialog
alert.accept() # Click the confirm button
alert.dismiss() # Click the cancel button
alert.text # Retrieve dialog text content
alert.send_keys("input") # Type text into the dialog input field
Switching Between Frames
Elements located inside <frame> or <iframe> tags cannot be accessed directly. You must first switch context to the frame containing the target element.
driver.switch_to.frame("frame_id") # Switch using frame id or name attribute
driver.switch_to.frame(0) # Switch by frame index
driver.switch_to.parent_frame() # Move up one level in frame hierarchy
driver.switch_to.default_content() # Return to the top-level document
Managing Multiple Browser Windows
When multiple windows exist in a browser session, use switch_to.window() to target the desired window.
driver.switch_to.window("window_name") # Switch focus to specific window
driver.current_window_handle # Retrieve current window handle
driver.window_handles # Retrieve all open window handles
Practical Example - Iterating through windows to find a specific one:
def switch_to_target_window(driver, target_title):
for handle in driver.window_handles:
driver.switch_to.window(handle)
if driver.title == target_title:
return True
return False
Practical Example - Switching to newly opened window:
def test_search_baidu(self):
self.driver.get("https://www.baidu.com/")
search_box = self.driver.find_element(By.ID, "kw")
search_box.send_keys("selenium")
self.driver.find_element(By.ID, "su").click()
# Open link in new tab
self.driver.find_element(By.PARTIAL_LINK_TEXT, "百度百科").click()
# Store current window
main_window = self.driver.current_window_handle
# Get all window handles
all_windows = self.driver.window_handles
# Switch to the newly opened window (second one)
for window in all_windows:
self.driver.switch_to.window(window)
if window != main_window:
break
# Now interact with elements in the new window
self.driver.find_element(By.ID, "query").send_keys("automation testing")
Handling unknown window locations:
def find_element_in_any_window(driver, by, locator, target_title):
original_window = driver.current_window_handle
for handle in driver.window_handles:
driver.switch_to.window(handle)
try:
element = driver.find_element(by, locator)
if driver.title == target_title:
return element
except NoSuchElementException:
continue
# Return to original window if not found
driver.switch_to.window(original_window)
return None
Simulating Mouse and Keyboard Interactions
The ActionChains class enables complex user interactions that simple WebElement methods cannot handle.
from selenium.webdriver.common.action_chains import ActionChains
action_builder = ActionChains(driver)
action_builder.click(element) # Left-click on element
action_builder.click() # Left-click on current element
action_builder.context_click(element) # Right-click (context menu)
action_builder.double_click(element) # Double-click
action_builder.click_and_hold(element) # Mouse down and hold
action_builder.move_to_element(element) # Hover over element
action_builder.drag_and_drop(source, target) # Drag source to target
action_builder.drag_and_drop_by_offset(source, x, y) # Drag by pixel offset
action_builder.perform() # Execute queued actions
action_builder.reset_actions() # Clear queued actions
Keyboard Operations with ActionChains:
from selenium.webdriver.common.keys import Keys
keyboard_actions = ActionChains(driver)
keyboard_actions.send_keys(Keys.ENTER) # Press Enter
keyboard_actions.send_keys_to_element(elem, "text") # Type into element
keyboard_actions.key_down(Keys.CONTROL).send_keys("a") # Ctrl+A
keyboard_actions.key_up(Keys.CONTROL) # Release modifier
keyboard_actions.key_down(Keys.SHIFT).send_keys("abc") # Type uppercase
keyboard_actions.key_up(Keys.SHIFT)
Key Categories:
- Character keys: a-z, 0-9
- Special keys: Tab, Enter, Space, Backspace, Escape
- Modifier keys: Alt, Shift, Control, Command
Executing JavaScript Code
Selenium's execute_script() method runs arbitrary JavaScript when native WebDriver methods are insufficient.
# Retrieve page title via JavaScript
title = driver.execute_script("return document.title;")
# Modify element style dynamically
target_element = driver.find_element(By.ID, "element_id")
driver.execute_script(
"arguments[0].setAttribute('style', arguments[1]);",
target_element,
"color: orange; border: 4px solid orange;"
)
# Show hidden element
driver.execute_script(
"document.getElementById('hidden_field').style.display = 'block';"
)
# Display alert
driver.execute_script("alert('Operation completed');")
# Execute asynchronous JavaScript
result = driver.execute_async_script("arguments[0](true);", callback_value)
File Upload Operations
File uploads in Selanium use the standard input element's send_keys() method.
driver.get("http://example.com/upload_page")
# Click upload trigger button
driver.find_element(By.CLASS_NAME, "upload-trigger").click()
# Send file path to the hidden file input
file_input = driver.find_element(By.XPATH, "//input[@type='file']")
file_input.send_keys(r"C:\test_files\sample_image.jpg")
Screenshot Capture
# Capture entire page screenshot
driver.save_screenshot("screenshot.png")
# Capture and return as base64 encoded PNG
base64_image = driver.get_screenshot_as_base64()
# Capture as PNG binary data
png_data = driver.get_screenshot_as_png()
Scrolling Page Content
JavaScript execution handles scroll operations that WebDriver cannot perform natively.
# Scroll to bottom of the page
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
# Scroll to top of the page
driver.execute_script("window.scrollTo(0, 0);")
# Scroll by specific pixel amount
driver.execute_script("window.scrollBy(0, 500);")
# Scroll element into view
target = driver.find_element(By.ID, "bottom_element")
driver.execute_script("arguments[0].scrollIntoView(true);", target)
# Smooth scroll to element
driver.execute_script(
"arguments[0].scrollIntoView({behavior: 'smooth', block: 'center'});",
target
)
Combined Practical Example
def complete_multi_step_task(driver):
# Handle authentication dialog
driver.get("https://secure-site.com")
driver.find_element(By.NAME, "username").send_keys("admin")
driver.find_element(By.NAME, "password").send_keys("secret")
driver.find_element(By.NAME, "submit").click()
# Switch to iframe containing main content
driver.switch_to.frame("content_frame")
# Hover to reveal hidden menu
menu_item = driver.find_element(By.ID, "main_menu")
ActionChains(driver).move_to_element(menu_item).perform()
# Click submenu item
driver.find_element(By.LINK_TEXT, "Settings").click()
# Execute JavaScript to manipulate DOM
driver.execute_script(
"document.querySelector('.status-indicator').textContent = 'Active';"
)
# Switch to default content and handle popup window
driver.switch_to.default_content()
trigger = driver.find_element(By.ID, "new_window_btn")
trigger.click()
# Wait and switch to new window
WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2))
for window in driver.window_handles:
driver.switch_to.window(window)
if "settings" in driver.title.lower():
break
# Capture screenshot of result
driver.save_screenshot("settings_page.png")