Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Selenium Tutorial

Introduction to Selenium

Selenium is an open-source suite of tools that automates web browsers. It is widely used for testing web applications and supports various programming languages such as Java, Python, C#, and Ruby. Selenium provides a playback tool for authoring tests without learning a test scripting language.

Components of Selenium

Selenium consists of several components:

  • Selenium WebDriver: A programming interface for creating and executing test scripts.
  • Selenium IDE: A browser extension that allows for the recording and playback of tests.
  • Selenium Grid: A tool that allows for running tests on different machines and browsers simultaneously.

Setting Up Selenium

Before you can start using Selenium, you need to set it up. Here’s how to do it for Python:

Step 1: Install Python and pip (Python package installer).

Step 2: Install the Selenium package using pip. Run the following command in your terminal:

pip install selenium

Step 3: Download the appropriate WebDriver for your browser (e.g., ChromeDriver for Chrome).

Your First Selenium Script

Now that you have set up Selenium, let’s write a simple script to open a webpage.

Here is an example of a basic Selenium script in Python:

from selenium import webdriver

# Create a new instance of the Firefox driver
driver = webdriver.Firefox()

# Navigate to a webpage
driver.get("http://www.example.com")

# Close the browser
driver.quit()

This script opens Firefox, navigates to "http://www.example.com", and then closes the browser.

Locating Elements

To interact with web elements, you need to locate them. Selenium provides various methods to find elements:

  • By ID: driver.find_element_by_id('element_id')
  • By Name: driver.find_element_by_name('element_name')
  • By XPath: driver.find_element_by_xpath('//tag[@attribute="value"]')
  • By CSS Selector: driver.find_element_by_css_selector('css.selector')

Interacting with Elements

After locating an element, you can perform actions like clicking, sending keys, and more:

Example of interacting with a text input:

# Locate the input element by name
input_element = driver.find_element_by_name('username')

# Send keys to the input element
input_element.send_keys('testuser')

Assertions in Selenium

Assertions are crucial for validating expected outcomes in your tests. Here’s an example using the assert statement:

Check if the title of the page is correct:

assert "Example Domain" in driver.title

Conclusion

Selenium is a powerful tool for automating web applications for testing purposes. With its various components and support for multiple programming languages, it is a popular choice among testers. By following this tutorial, you should have a foundational understanding of how to get started with Selenium.