Selenium Browser Operations
Selenium can not only operate on web page elements, but also control the browser's own behavior, such as managing windows, handling popups, manipulating Cookies, executing JavaScript, and so on.
The following are common browser operations in Selenium and their descriptions:
| Operation Type | Method | Description |
|---|---|---|
| Open a new window | execute_script("window.open('URL');") | Open a new window using JavaScript. |
| Switch window | switch_to.window(window_handle) | Switch to the specified window handle. |
| Close window | close() | Close the current window. |
| Maximize window | maximize_window() | Maximize the browser window. |
| Set window size | set_window_size(width, height) | Set the size of the browser window. |
| Full-screen mode | fullscreen_window() | Set the browser window to full-screen mode. |
| Open a web page | get(url) | Open the specified URL. |
| Forward and back | back()andforward() | Go back to the previous page or forward to the next page. |
| Refresh page | refresh() | Refresh the current page. |
| Handle Alert popup | switch_to.alertIn combination withaccept()ordismiss() | Handle the Alert popup, clicking OK or Cancel. |
| Handle Confirm popup | switch_to.alertIn combination withaccept()ordismiss() | Handle the Confirm popup, clicking OK or Cancel. |
| Handle Prompt popup | switch_to.alertIn combination withsend_keys()andaccept()ordismiss() | Handle the Prompt popup, enter text, then click OK or Cancel. |
| Add Cookie | add_cookie(cookie_dict) | Add the specified Cookie. |
| Get Cookie | get_cookie(name)orget_cookies() | Get the specified Cookie or all Cookies. |
| Delete Cookie | delete_cookie(name)ordelete_all_cookies() | Delete the specified Cookie or all Cookies. |
| Execute JavaScript | execute_script(script) | Execute the specified JavaScript code. |
| Get the JavaScript return value | execute_script("return ...") | Execute JavaScript and return the result. |
| Switch to iframe | switch_to.frame(iframe_element) | Switch to the specified iframe. |
| Switch back to the main page | switch_to.default_content() | Switch back to the main page. |
1. Handling Browser Popups (alert, confirm, prompt)
In web applications, popups (such as alert, confirm, prompt) are a common user interaction method. Selenium providesAlerta class to handle these popups.
1.1 Handling alert Popups
alertThe alert popup is typically used to display a message, and the user can only click the "OK" button to close it.
Example
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.alert import Alert
# Set the correct driver path
service = ChromeService(executable_path="./chromedriver-mac-arm64/chromedriver")
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(service=service, options=options)
# Open the web page
driver.get("https://example.com")
# Trigger the alert popup
driver.execute_script("alert('This is an alert popup');")
# Switch to the alert popup
alert = Alert(driver)
# Get the popup text
print(alert.text)
# Click the "OK" button to close the popup
alert.accept()
# Close the browser
driver.quit()
1.2 Handling confirm Popups
confirmThe confirm popup is typically used to confirm an action, and the user can choose "OK" or "Cancel".
Example
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.alert import Alert
# Set the correct driver path
service = ChromeService(executable_path="./chromedriver-mac-arm64/chromedriver")
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(service=service, options=options)
# Open the web page
driver.get("https://example.com")
# Trigger the confirm popup
driver.execute_script("confirm('This is a confirm popup');")
# Switch to the confirm popup
alert = Alert(driver)
# Get the popup text
print(alert.text)
# Click the "OK" button
alert.accept()
# Or click the "Cancel" button
# alert.dismiss()
# Close the browser
driver.quit()
1.3 Handling prompt Popups
promptThe prompt popup is typically used to obtain user input; the user can enter text and choose "OK" or "Cancel".
Example
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.alert import Alert
# Set the correct driver path
service = ChromeService(executable_path="./chromedriver-mac-arm64/chromedriver")
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(service=service, options=options)
# Start the browser
driver = webdriver.Chrome()
# Open the web page
driver.get("https://example.com")
# Trigger the prompt popup
driver.execute_script("prompt('This is a prompt popup');")
# Switch to the prompt popup
alert = Alert(driver)
# Get the popup text
print(alert.text)
# Enter text
alert.send_keys("User input")
# Click the "OK" button
alert.accept()
# Or click the "Cancel" button
# alert.dismiss()
# Close the browser
driver.quit()
2. Switching Windows and Tabs
In web applications, users may open multiple windows or tabs. Selenium providesswitch_to.window()methods to switch windows or tabs.
2.1 Switching Windows
Example
from selenium.webdriver.chrome.service import Service as ChromeService
# Set the correct driver path
service = ChromeService(executable_path="./chromedriver-mac-arm64/chromedriver")
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(service=service, options=options)
# Open the first window
driver.get("https://example.com")
# Open the second window
driver.execute_script("window.open('https://example.org');")
# Get all window handles
window_handles = driver.window_handles
# Switch to the second window
driver.switch_to.window(window_handles[1])
# Operate in the second window
print(driver.title)
# Switch back to the first window
driver.switch_to.window(window_handles[0])
# Close the browser
driver.quit()
2.2 Switching Tabs
Switching tabs is similar to switching windows, because each tab is an independent window handle.
Example
from selenium.webdriver.chrome.service import Service as ChromeService
# Set the correct driver path
service = ChromeService(executable_path="./chromedriver-mac-arm64/chromedriver")
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(service=service, options=options)
# Open the first tab
driver.get("https://example.com")
# Open the second tab
driver.execute_script("window.open('https://example.org');")
# Get all tab handles
tab_handles = driver.window_handles
# Switch to the second tab
driver.switch_to.window(tab_handles[1])
# Operate in the second tab
print(driver.title)
# Switch back to the first tab
driver.switch_to.window(tab_handles[0])
# Close the browser
driver.quit()
3. Handling iframes
iframeAn iframe is another web page embedded in a web page. Selenium providesswitch_to.frame()methods to switch to an iframe.
3.1 Switching to an iframe
Example
from selenium.webdriver.chrome.service import Service as ChromeService
# Set the correct driver path
service = ChromeService(executable_path="./chromedriver-mac-arm64/chromedriver")
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(service=service, options=options)
# Open the web page
driver.get("https://example.com")
# Switch to the iframe
iframe = driver.find_element_by_tag_name("iframe")
driver.switch_to.frame(iframe)
# Operate in the iframe
print(driver.page_source)
# Switch back to the main page
driver.switch_to.default_content()
# Close the browser
driver.quit()
3.2 Switching Back to the Main Page
After completing operations in the iframe, you can useswitch_to.default_content()methods to switch back to the main page.
Example
driver.switch_to.default_content()
4. Browser Cookies Operations
Selenium providesget_cookies()、add_cookie()、delete_cookie()and other methods to operate on browser Cookies.
4.1 Getting Cookies
Example
from selenium.webdriver.chrome.service import Service as ChromeService
# Set the correct driver path
service = ChromeService(executable_path="./chromedriver-mac-arm64/chromedriver")
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(service=service, options=options)
# Open the web page
driver.get("https://example.com")
# Get all Cookies
cookies = driver.get_cookies()
print(cookies)
# Close the browser
driver.quit()
4.2 Adding a Cookie
Example
from selenium.webdriver.chrome.service import Service as ChromeService
# Set the correct driver path
service = ChromeService(executable_path="./chromedriver-mac-arm64/chromedriver")
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(service=service, options=options)
# Open the webpage
driver.get("https://example.com")
# Add Cookie
driver.add_cookie({"name": "test", "value": "123"})
# Get all cookies
cookies = driver.get_cookies()
print(cookies)
# Close the browser
driver.quit()
4.3 Deleting a Cookie
Example
from selenium.webdriver.chrome.service import Service as ChromeService
# Set the correct driver path
service = ChromeService(executable_path="./chromedriver-mac-arm64/chromedriver")
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(service=service, options=options)
# Open the webpage
driver.get("https://example.com")
# Add Cookie
driver.add_cookie({"name": "test", "value": "123"})
# Delete Cookie
driver.delete_cookie("test")
# Get all cookies
cookies = driver.get_cookies()
print(cookies)
# Close the browser
driver.quit()
5. Executing JavaScript Code
Selenium providesexecute_script()methods to execute JavaScript code.
5.1 Executing JavaScript Code
Example
from selenium.webdriver.chrome.service import Service as ChromeService
# Set the correct driver path
service = ChromeService(executable_path="./chromedriver-mac-arm64/chromedriver")
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(service=service, options=options)
# Open the webpage
driver.get("https://example.com")
# Execute JavaScript code
driver.execute_script("alert('This is a JavaScript popup');")
# Close the browser
driver.quit()
5.2 Getting the JavaScript Return Value
Example
from selenium.webdriver.chrome.service import Service as ChromeService
# Set the correct driver path
service = ChromeService(executable_path="./chromedriver-mac-arm64/chromedriver")
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(service=service, options=options)
# Open the webpage
driver.get("https://example.com")
# Execute JavaScript code and get the return value
result = driver.execute_script("return document.title;")
print(result)
# Close the browser
driver.quit()
6. Comprehensive Example
The following is a complete example showing how to use various browser operations:
Example
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
# Set the correct driver path
service = ChromeService(executable_path="./chromedriver-mac-arm64/chromedriver")
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(service=service, options=options)
# Open the webpage
driver.get("https://www.example.com")
# Maximize the window
driver.maximize_window()
# Add Cookie
driver.add_cookie({"name": "test", "value": "123"})
# Get Cookie
cookie = driver.get_cookie("test")
print("Cookie:", cookie)
# Execute JavaScript
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
# Handle the Alert popup
driver.execute_script("alert('Hello, Selenium!');")
alert = driver.switch_to.alert
print("Popup text:", alert.text)
alert.accept()
# Switch to iframe
iframe = driver.find_element(By.ID, "iframe-id")
driver.switch_to.frame(iframe)
# Switch back to the main page
driver.switch_to.default_content()
# Close the browser
driver.quit()