Starting with Selenium automation and Python
Selenium is a powerful tool for automating web applications for testing purposes. It allows developers and testers to simulate user interactions with a browser, making it an essential part of automated testing workflows.
1. Installing Selenium
# Install Selenium using pip
pip install selenium
# Download the WebDriver (e.g., ChromeDriver) from:
# https://sites.google.com/chromium.org/driver/
2. Setting Up Selenium with Python
from selenium import webdriver
# Set up WebDriver (Make sure you have ChromeDriver installed)
driver = webdriver.Chrome()
# Open a website
driver.get("https://www.example.com")
# Close the browser
driver.quit()
3. Finding Elements
# Locate an element by ID
element = driver.find_element("id", "username")
# Locate an element by Name
element = driver.find_element("name", "password")
# Locate an element by XPath
element = driver.find_element("xpath", "//input[@type='submit']")
4. Interacting with Elements
# Enter text in an input field
element.send_keys("my_username")
# Click a button
button = driver.find_element("id", "submit")
button.click()
5. Handling Dropdowns
from selenium.webdriver.support.ui import Select
# Locate the dropdown element
dropdown = Select(driver.find_element("id", "country"))
# Select by visible text
dropdown.select_by_visible_text("United States")
6. Handling Alerts
# Accept an alert
alert = driver.switch_to.alert
alert.accept()
7. Running a Simple Test
import unittest
class TestGoogleSearch(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome()
def test_google_search(self):
self.driver.get("https://www.google.com")
search_box = self.driver.find_element("name", "q")
search_box.send_keys("Selenium WebDriver")
search_box.submit()
self.assertIn("Selenium WebDriver", self.driver.title)
def tearDown(self):
self.driver.quit()
if __name__ == "__main__":
unittest.main()
8. Headless Mode for Faster Tests
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument("--headless")
# Run Chrome in headless mode
driver = webdriver.Chrome(options=options)
9. Taking Screenshots
# Capture a screenshot
driver.save_screenshot("screenshot.png")
10. Closing the Browser Properly
# Close a single tab
driver.close()
# Quit the browser session completely
driver.quit()