Real-World Examples and Demo Scripts in Selenium Python Automation

 

9. Real-World Examples and Demo Scripts in Selenium Automation

We will provide real-world examples and case studies to showcase the application of these best practices in practical scenarios. This will help you understand the implementation of these techniques in real automation projects.

9.1. Launch Selenium Practice Form Script

This demo script will open the Chrome browser and open the selenium.dev website.


from selenium import webdriver

browser = webdriver.Chrome("chromedriver.exe")
browser.get('https://www.techlistic.com/p/selenium-practice-form.html')


9.2. Search the keyword "Selenium" in the pypi.org search box

In this script, we'll launch Chrome browser, open pypi.org, and then type ""Selenium" in the search bar and will click enter.


from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys

# Launch Chrome browser
browser = webdriver.Chrome("chromedriver.exe")
# Open pypi.org
browser.get('https://pypi.org/project/selenium/')

# Maximize Browser Window
browser.maximize_window()

# Set wait time of 30 secs
browser.implicitly_wait(30)

# Type "Selenium" in search bar
browser.find_element(By.ID, 'search').send_keys("Selenium")
# Click Enter
browser.find_element(By.ID, 'search').send_keys(Keys.RETURN)


9.3. Automate Techlistic Demo Sign-up form

In this demo script, we have automated Techlistic.com's demo sign-up form using all the Selenium Webdriver commands. And in this script, unittest framework has been used. The setUp and tearDown methods are part of unittest framework in Python. The setUp method executes before the test method and the tearDown method executes after the test method.

import time
import unittest

from selenium import webdriver
from selenium.webdriver.common.by import By

# Variables
driver_path='chromedriver.exe'
navigate_url = "https://www.techlistic.com/p/selenium-practice-form.html"

class DemoqaTesting(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Chrome(driver_path)
        self.driver.maximize_window()
        self.driver.get(navigate_url)
        self.driver.implicitly_wait(30)

    def tearDown(self):
        self.driver.quit()

    def test_automate_form(self):
        # Enter First Name
        first_name = self.driver.find_element(By.NAME,'firstname')
        first_name.send_keys('Jassi')

        # Enter Last Name
        last_name = self.driver.find_element(By.NAME,'lastname')
        last_name.send_keys('Maurya')

        # Click on Gender Radio button
        gender = self.driver.find_element(By.ID, 'sex-1')
        print(gender.is_selected())
        gender.click()

        # Enter DOB
        dob = self.driver.find_element(By.ID,'datepicker')
        dob.clear()
        dob.send_keys('19 Mar 1990')

        # Select Profession checkbox
        profession = self.driver.find_element(By.ID,'profession-1')
        profession.click()

        # Select Automation tool checkbox
        automation_tool = self.driver.find_element(By.ID,'tool-2')
        automation_tool.click()

        # Click Submit button
        submit_button = self.driver.find_element(By.ID,'submit')
        submit_button.click()

        time.sleep(5)


if __name__=='__main__':
    unittest.main()

9.4. Automate Example Scenarios for Dummy e-Comm Website Functionalities:

To illustrate the automation of common web application functionalities, let's consider the following scenarios:

Scenario 1: Login

  • Navigate to the login page
  • Fill in the required fields with valid data
  • Submit the login form
  • Verify the successful login message or the user's profile page

Scenario 2: Search Functionality

  • Open the home page
  • Enter a search query in the search field
  • Click on the search button
  • Verify that the search results are displayed correctly

Scenario 3: Adding Items to Cart

  • Browse to a product category page
  • Select a specific product
  • Add the product to the cart
  • Verify that the item appears in the cart
Scenario 4: Complete and Verify Checkout
  • Browse to a product category page
  • Select a specific product
  • Add the product to the cart
  • Verify that the item appears in the cart
  • Continue Checkout and enter checkout details.
  • Click the Complete Checkout button.
  • Verify Successful Checkout Button.

Here's the code that includes the checkout process after adding an item to the cart:

python
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # Set up the driver driver = webdriver.Chrome() # Change this to the appropriate web driver if needed driver.maximize_window() # Navigate to the login page driver.get("https://www.saucedemo.com/") # Perform login username = "standard_user" password = "secret_sauce" username_field = WebDriverWait(driver, 10).until( EC.visibility_of_element_located((By.ID, "user-name")) ) username_field.send_keys(username) password_field = driver.find_element(By.ID, "password") password_field.send_keys(password) login_button = driver.find_element(By.ID, "login-button") login_button.click() # Verify successful login inventory_page_title = WebDriverWait(driver, 10).until( EC.title_contains("Swag Labs") ) if "Swag Labs" in driver.title: print("Login successful!") else: print("Login failed.") # Perform search functionality search_field = WebDriverWait(driver, 10).until( EC.visibility_of_element_located((By.ID, "search-box")) ) search_field.send_keys("backpack") search_button = driver.find_element(By.ID, "search-button") search_button.click() # Verify search results search_results = driver.find_elements(By.XPATH, "//div[@class='inventory_item_name']") if len(search_results) > 0: print("Search results found.") else: print("No search results found.") # Add item to cart add_to_cart_button = driver.find_element(By.XPATH, "//button[text()='Add to cart']") add_to_cart_button.click() # Verify item added to cart cart_badge = WebDriverWait(driver, 10).until( EC.visibility_of_element_located((By.XPATH, "//span[@class='shopping_cart_badge']")) ) cart_items_count = int(cart_badge.text) if cart_items_count > 0: print(f"Item added to cart. Cart count: {cart_items_count}") else: print("Item not added to cart.") # Close the browser driver.quit()
Let's break down the code step-by-step: 1. Importing the necessary modules:
  • from selenium import webdriver: Importing the Selenium WebDriver module, which provides the necessary tools for browser automation.
  • from selenium.webdriver.common.by import By: Importing the By class, which is used to locate web elements by different strategies such as ID, class name, XPath, etc.
  • from selenium.webdriver.support.ui import WebDriverWait: Importing the WebDriverWait class, which provides explicit wait functionality to wait for certain conditions to be met before proceeding with the code execution.\
  • from selenium.webdriver.support import expected_conditions as EC: Importing the expected_conditions module from Selenium's support package, which provides various conditions to be used with WebDriverWait.

2. Setting up the driver:
  • driver = webdriver.Chrome(): Creating an instance of the Chrome WebDriver. This sets up the Chrome browser for automation. You can change the web driver to the appropriate one based on your browser choice.
  • driver.maximize_window(): Maximizing the browser window to ensure the content is fully visible.

3. Navigating to the login page: driver.get("https://www.saucedemo.com/"): Opening the specified URL in the browser.
4. Performing login:
  • Providing the login credentials by finding the username and password fields using WebDriverWait and locating the elements by their IDs.
  • username_field.send_keys(username): Entering the value of the username variable into the username field.
  • password_field.send_keys(password): Entering the value of the password variable into the password field.
  • login_button.click(): Click the login button to submit the form.

5. Verifying successful login:
  • Using WebDriverWait to wait for the title of the page to contain "Swag Labs" (the expected title after successful login).
  • Checking if the page title contains "Swag Labs" to determine if the login was successful.

6. Performing search functionality:
  • Finding the search field using WebDriverWait and locating the element by its ID.
  • Entering the search keyword "backpack" into the search field.
  • Finding the search button and clicking it to initiate the search.

7. Verifying search results:
  • Using WebDriverWait to wait for the presence of search results.
  • Checking if the search results are found by verifying if the length of the search results is greater than zero.
8. Adding an item to the cart:
  • Finding the "Add to cart" button using an XPath expression and clicking it.

9. Verifying item added to cart:
  • Using WebDriverWait to wait for the visibility of the cart badge (indicating the number of items in the cart).
  • Retrieving the text from the cart badge and converting it to an integer.
  • Checking if the cart items count is greater than zero to confirm that the item was added to the cart.

10. Closing the browser:
  • driver.quit(): Quitting the browser and ending the WebDriver session.
  • This code demonstrates a typical Selenium automation workflow for logging in, performing a search, adding an item to the cart, and verifying the results. You can modify and expand upon this code to suit your specific needs.

Author
Passionately working as an Automation Developer for more than a decade.

Comments

Popular posts from this blog

How Tesla is Revolutionizing AI and Energy in 2025

Python Behave Tutorial: A Comprehensive Guide to Behavior-Driven Development (BDD)

What Role Graphic Design Services Play in Marketing

17 Best Demo Websites for Automation Testing Practice

Top 11 Interview Blunders That Can Cost You the Job: Expert Tips to Avoid Them

Selenium IDE Tutorial: How to Automate Web Testing with Easy-to-Use Interface

Mastering Selenium Practice: Automating Web Tables with Demo Examples

Top Free YouTube Download Apps: Download YouTube Videos Software Free

Top 10 Highly Paid Indian CEOs in the USA

Mastering Software Testing Techniques: Boundary Value Analysis to State Transition