To handle browser tabs in Selenium using Python, you can use methods to switch between windows or tabs using their handles. Here’s a guide on how to open a new tab, switch between tabs, and close
- Selenium Features
- Selenium Installation
- Selenium Locators
- XPath Fundamentals
- CSS Selectors Methods
- Different Browsers Execution
- find_element & find_elements
- Check Enabled Status
- Check Displayed Status
- Check Selected Status
- Selenium Waits
- Send_keys Method
- Click Method
- Get Text
- Get Attribute Value
- Get Current URL
- Forward, Back, Refresh
- Take Screenshot
- Handle Browser Tabs
- Handle iframe
- Mouse Hover
- Context-Click
- Drag & Drop
- Handle Alerts
- Handle Dropdown
- Execute Javascript
- Scroll To element
- Headless Mode Execution
- Chrome Options
- Keyboard Action
Example Code
from selenium import webdriver
import time
# Initialize the WebDriver (e.g., using Chrome)
driver = webdriver.Chrome()
driver.implicitly_wait(10)
# Open the first URL
driver.get("https://www.facebook.com")
print("Current tab URL:", driver.current_url)
# Save the original window handle
original_tab = driver.current_window_handle
# Open a new tab using JavaScript (useful for browsers like Chrome)
driver.execute_script("window.open('https://www.google.com', '_blank');")
# Get the list of all window handles (tabs)
window_handles = driver.window_handles
print("All window handles:", window_handles)
# Switch to the new tab
driver.switch_to.window(window_handles[1])
print("Switched to new tab URL:", driver.current_url)
# Pause for a few seconds (optional)
time.sleep(2)
# close google page
driver.close()
# Switch back to the original tab
driver.switch_to.window(original_tab)
print("Switched back to original tab URL:", driver.current_url)
time.sleep(2)
# Close the browser
driver.quit()
Explanation:
driver.window_handles
: Returns a list of window handles (IDs) for all the open tabs/windows.driver.switch_to.window(handle)
: Switches the WebDriver’s focus to the specified window handle.driver.execute_script("window.open('URL', '_blank');")
: Opens a new tab using JavaScript.- To close a specific tab, you can use
driver.close()
while the focus is on that tab.
This approach allows you to manage multiple tabs efficiently, such as switching between them or closing specific ones as needed.