How to Open New Tabs with Selenium in Python
When performing automated web testing, efficiently opening multiple websites can significantly improve speed. Selenium WebDriver allows you to manage multiple tabs within a single browser instance, reducing overhead compared to creating new instances for each website.
To achieve this, Selenium emulates keyboard shortcuts for opening and closing tabs. On macOS, you can use COMMAND T and COMMAND W, while on other operating systems, CONTROL T and CONTROL W are commonly used.
Here's how to implement this functionality in Python using Selenium WebDriver:
from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() driver.get("http://www.google.com/") # Open a new tab driver.find_element_by_tag_name('body').send_keys(Keys.COMMAND + 't') # COMMAND + t on macOS, CONTROL + t on other OSs # Load a page driver.get('http://stackoverflow.com/') # Perform your testing actions here... # Close the tab driver.find_element_by_tag_name('body').send_keys(Keys.COMMAND + 'w') # COMMAND + w on macOS, CONTROL + w on other OSs driver.close()
By using this approach, you can open and close multiple tabs dynamically while testing different websites, significantly improving the efficiency of your automation scripts.
The above is the detailed content of How to Efficiently Open and Close Multiple Browser Tabs with Selenium in Python?. For more information, please follow other related articles on the PHP Chinese website!