Introduction:
Let’s start our story about Selenium! Selenium is a handy tool many people use to test websites. It helps developers and testers perform various actions on a website automatically, like clicking buttons or filling out forms. In our story, we’ll focus on using Selenium with Python, a language that’s popular for automation. Here is a step by step to begin your adventure with Selenium and Python. Some of the renowned Selenium Python frameworks are: PyTest, Robot Framework and Behave.
This post provides an introduction to Selenium with Python tutorials, covering important topics such as installation, writing your first script, element identification, and handling various interactions. In the next series, we will deep dive into utilizing frameworks to create advanced automation scripts with Selenium and Python.
Setting up the Environment
In this section, we’ll explore the initial preparations for using Selenium with Python, involving the installation of Python, Selenium, and the required WebDrivers to ensure smooth functionality. Simply follow the steps we’ll discuss, and you’ll have everything configured correctly for your Selenium journey with Python. Let’s begin to ensure a proper setup for convenient development and testing with Selenium and Python.
Installing Python
- Visit the official Python hub at https://www.python.org and acquire the most recent Python release tailored for your operating system.
- After securing the latest version, execute the downloaded installer, and seamlessly progress through the provided instructions for a smooth installation.
- Make sure to check the box that says “Add Python to PATH” during the installation process.
- You can verify the installation by opening the command prompt and running the command python –version. It should display the installed Python version. Or you can use pip3 –version
Installing Selenium
- Open a command prompt or terminal.
- Run the following command to install Selenium using pip:
pip install selenium
Pip3 can also be used, it will download and install the Selenium library along with its dependencies.
Installing WebDrivers
- To enable browser automation, it’s essential to obtain and install the relevant WebDriver tailored to your chosen browser.
- Chrome, Firefox, and Safari are among the most commonly utilized browsers in Selenium. In this guide, we’ll outline the steps specifically for Chrome, the widely used browser.
Installing ChromeDriver (for Google Chrome):
- Refer to the link below to download Chromedriver: https://sites.google.com/a/chromium.org/chromedriver/downloads.
- Download the ChromeDriver version that sync with your installed Google Chrome version.
- Extract the downloaded file and then we need to move the extracted chromedriver executable to a directory which is included in your system’s PATH variable.
An Autonomous Bot to Test your Apps
Locating Web Elements
Web Elements identification by using the right locators is important when working with Selenium and Python. Though methods like ID, Name, Class Name, Link Text, and CSS Selector work well, it’s recommended to give preference to ID and Name over XPath if they are present. Also, developers can make use of browser developer tools to help accurately identify elements.
Locator Method |
Example |
By ID | elementById = driver.find_element_by_id(“element-ID”) |
By Name | element = driver.find_element_by_name(“element-NAME”) |
By Class Name | element = driver.find_element_by_class_name(“element-CLASS”) |
By Tag Name | elements = driver.find_elements_by_tag_name(“tag-NAME”) |
By Link Text | link = driver.find_element_by_link_text(“Text on the LINK”) |
By Partial Link Text | link = driver.find_element_by_partial_link_text(“Partial TEXT”) |
By CSS Selector | elementByCssSelector = driver.find_element_by_css_selector(“CSS-selector”) |
By XPath | element = driver.find_element_by_xpath(“XPATH-expression”) |
Use these locator techniques into your Selenium scripts to precisely identify web elements based on their specific attributes or criteria, aligning with the elements you’re targeting on your webpage.
Interacting with Web Elements
Engaging with web elements is a key aspect when dealing with Selenium and Python. It enables us to carry out different actions in our test scripts. In this section, we will delve into essential operations like clicking elements, entering values into text boxes, managing alerts, pop-ups, dropdowns, and more. Proficiency in these interactions is crucial for creating efficient and thorough test scripts with Selenium and Python.
Here are instances of various interactions with web elements using Selenium with Python:
Clicking Elements
# Clicking a button
buttonElement = driver.find_element_by_id(“button_ID”)
buttonElement.click()
# Clicking a link
linkElement = driver.find_element_by_link_text(“Click HERE”)
linkElement.click()
Sending Keys (Typing into input fields)
# Typing into a text field
text_fieldElement = driver.find_element_by_id(“text_field_ID”)
text_fieldElement.send_keys(“Hello! World!”)
# Sending special keys (e.g., Enter key)
text_fieldElement.send_keys(Keys.ENTER)
Clearing Text
# Clearing a text field
text_fieldElement = driver.find_element_by_id(“text_field_ID”)
text_fieldElement.clear()
Extracting Text
# Extracting text from an element
elementText = driver.find_element_by_id(“element-ID”)
text = element.text
print(“Extracted Text:”, text)
Handling Dropdowns
from selenium.webdriver.support.ui import Select
# Selecting an option by visible text
dropdown = Select(driver.find_element_by_id(“dropdown-id”))
dropdown.select_by_visible_text(“Option 1”)
# Selecting an option by value
dropdown.select_by_value(“option_value”)
# Selecting an option by index
dropdown.select_by_index(2)
Working with Checkboxes and Radio Buttons
# Clicking a checkbox
checkbox = driver.find_element_by_id(“checkbox-id”)
checkbox.click()
# Clicking a radio button
radio_button = driver.find_element_by_id(“radio-button-id”)
radio_button.click()
Handling Alerts and Pop-ups
# Accepting an alert
alert = driver.switch_to.alert
alert.accept()
# Dismissing an alert
alert.dismiss()
# Entering text in an alert
alert.send_keys(“Text for the alert”)
alert.accept()
Don’t forget to import the required modules/classes and substitute the element locators (“element-id,” “button-id,” etc.) with suitable locators according to the HTML structure of your webpage.
These examples demonstrate various usual interactions with web elements using Selenium with Python. Feel free to adjust them based on your particular needs and the structure of the website you are automating.
Writing Your First Selenium Script
In this part, we will create our first example script using Selenium with Python. We suggest you run this script on your computer first before moving on to the rest of this blog. Doing this will make sure your setup is right and that you can run Selenium scripts with Python without any problems. So, let’s begin and run our first script to check that everything is set up properly for your Selenium-Python development setup.
In this example, we will use the website “https://qa-practice.netlify.app/bugs-form.html” and the scenario is to open the URL and then validate the title, after validation we have to quit the driver.
from selenium import webdriver
# Set the path to your ChromeDriver exe file
chromeDriver_path = ‘path/to/chromedriver.exe’
# Create an instance of Chrome driver
driver = webdriver.Chrome(executable_path = chromeDriver_path)
# Navigate to the website
driver.get(“https://qa-practice.netlify.app/bugs-form.html”)
# Validate the title
expected_title = “Bug Report Form”
actual_title = driver.title
if expected_title == actual_title:
print(“Title validation successful!”)
else:
print(“Title validation failed. Expected:”, expected_title, “Actual:”, actual_title)
# Close the browser
driver.quit()
Hope by now you’ve installed the Selenium library and the correct WebDriver (like ChromeDriver), as we have discussed earlier in this post. Now, we need to save the code in a Python file, for example, demo_script.py, and run it by just navigating to the folder where the file is present and use “python demo_script.py”. The script should open a website, check its title, and provide the test results. After that, it will close the browser.
Refer the official github here
Advanced Interactions
In this section we will discuss advanced interactions commonly used in web automation with Selenium and Python. We will learn two important interactions: Mouse Actions (Drag and Drop, Double Click), Keyboard Actions (Keys, Combining Keys). By using these advanced interactions, you will be equipped with skills to efficiently automate web applications.
Let’s discuss the examples of advanced interactions using Selenium with Python:
Mouse Actions (Drag and Drop, Double Click)
from selenium.webdriver import ActionChains
# Performing drag and drop action
source_element = driver.find_element_by_id(“source-element-ID”)
target_element = driver.find_element_by_id(“target-element-ID”)
actions = ActionChains(driver)
actions.drag_and_drop(source_element, target_element).perform()
# Performing double click action
element = driver.find_element_by_id(“element-ID”)
actions = ActionChains(driver)
actions.double_click(element).perform()
Keyboard Actions (Keys, Combining Keys)
from selenium.webdriver.common.keys import Keys
# How to send keys to an input field
text-fieldElement = driver.find_element_by_id(“text_field_ID”)
text-fieldElement.send_keys(“Hello! World!”)
# How to combine multiple keys (for example Ctrl+A to select all text)
text-fieldElement.send_keys(Keys.CONTROL + “a”)
Conclusion:
Using Selenium along with Python, you can proficiently automate web applications by performing operations on various web elements. For example, you can click buttons, check if things are correct, and handle different situations on webpages. In this blog we have also explored some advanced actions like using the mouse and keyboard, dealing with different parts of a webpage, and one demo script to start your journey with Selenium python automation. This gives you the power to handle a variety of challenges in web automation.
In the upcoming posts, we’ll go deeper into topics like waiting, taking screenshots, handling problems, and using popular tools for testing. Keep in mind that Selenium with Python opens up many possibilities for testing and automating tasks on the web. As you continue learning, try out different features, experiment with finding elements on a webpage, and adopt good practices to improve your testing scripts. Stay tuned for more detailed tutorials that will refine your skills and empower you to create effective and sophisticated automated solutions.