Debug School

rakesh kumar
rakesh kumar

Posted on

Write a test script using Apache POI in selenium python

write a program How to read Excel File in using Apache POI API

write a program How to How to read Data of Cells in Excel spreadsheet without Iterator

write a program How to send multiple sets of Data from Excel Sheet

Create an Excel workbook named "data_driven_tests.xlsx" with two sheets:

  1. "TestCases" - This sheet will contain test cases, each with a test case ID, action (e.g., "Login," "Search," "Logout"), and any additional data required for the action.
  2. "Results" - This sheet will be initially empty and will be used to store the test results. in selenium python with example and output

Write a Python script that uses Apache POI (openpyxl) and Selenium to perform the following tasks:

  1. Read test cases from the "TestCases" sheet.
  2. For each test case, execute the specified action on a sample website (you can use any website for this assignment).
  3. Capture the results (e.g., pass or fail) of each test case.
  4. Write the test results (test case ID, action, result) to the "Results" sheet . Implement error handling for each test case to capture exceptions or unexpected behavior during test execution.

Provide detailed logging for each test case, including success and failure information.
Use a separate configuration sheet to store website URLs, locators, and other configuration data.
Handle different types of actions (e.g., login, search, form submission) and data input based on the action type.

When the script is executed, it should read test cases from the "TestCases" sheet, perform the specified actions on the website, and write the results to the "Results" sheet.
The "Results" sheet should provide clear information about which test cases passed and which failed

write a program How to read Excel File using Apache POI API

To read an Excel file using the Apache POI API in Selenium with Python, you can use the openpyxl library, which is a Python package for working with Excel files. Here's a simple example:

Install openpyxl:
If you haven't already, install the openpyxl library using pip:

pip install openpyxl
Enter fullscreen mode Exit fullscreen mode

Create an Excel File:
Create an Excel file (e.g., "example.xlsx") with some data. For this example, create a simple Excel file with the following data:

| Name    | Age |
| Alice   | 30  |
| Bob     | 25  |
| Carol   | 35  |
Enter fullscreen mode Exit fullscreen mode

Selenium Python Program:
Here's a Python program that uses the openpyxl library to read data from the Excel file and print it.

import openpyxl

# Load the Excel file
workbook = openpyxl.load_workbook("example.xlsx")

# Select the desired sheet (e.g., "Sheet1")
sheet = workbook["Sheet1"]

# Iterate through the rows and print the data
for row in sheet.iter_rows(values_only=True):
    name, age = row
    print(f"Name: {name}, Age: {age}")

# Close the Excel file
workbook.close()
Enter fullscreen mode Exit fullscreen mode

Run the Program:
Save the Python program to a file (e.g., "read_excel.py") and execute it using Python:

python read_excel.py
Output:
When you run the program, it will read the data from the Excel file and print it to the console. The output should look like this:

Name: Alice, Age: 30
Name: Bob, Age: 25
Name: Carol, Age: 35
Enter fullscreen mode Exit fullscreen mode

This program demonstrates how to read data from an Excel file using the openpyxl library, which is a common approach for working with Excel files in Selenium Python automation. You can extend this example to perform various data-driven testing tasks by reading test data from Excel files and using it in your Selenium test scripts.

write a program How to How to read Data of Cells in Excel spreadsheet without Iterator

To read data from specific cells in an Excel spreadsheet using Apache POI API in Selenium with Python without using an iterator, you can directly access the cells by specifying their row and column indices. Here's an example:

Install Apache POI:
If you haven't already, you need to download the Apache POI library (HSSF for .xls or XSSF for .xlsx) and add it to your Java project's classpath. For this example, we'll use XSSF for .xlsx files.

Create an Excel File:
Create an Excel file (e.g., "example.xlsx") with some data. For this example, create a simple Excel file with the following data:

| Name    | Age |
| Alice   | 30  |
| Bob     | 25  |
| Carol   | 35  |
Enter fullscreen mode Exit fullscreen mode

Selenium Python Program:
Here's a Python program that uses Apache POI (specifically, XSSF) to read data from specific cells in the Excel file without using an iterator:

from openpyxl import load_workbook

# Load the Excel file
workbook = load_workbook("example.xlsx")

# Select the desired sheet (e.g., "Sheet1")
sheet = workbook["Sheet1"]

# Read data from specific cells
name = sheet.cell(row=2, column=1).value
age = sheet.cell(row=2, column=2).value

print(f"Name: {name}, Age: {age}")

# Close the Excel file
workbook.close()
Enter fullscreen mode Exit fullscreen mode

Run the Program:
Save the Python program to a file (e.g., "read_specific_cells.py") and execute it using Python:

python read_specific_cells.py
Output:
When you run the program, it will read data from the specified cells in the Excel file and print it to the console. The output should look like this:

Name: Alice, Age: 30
Enter fullscreen mode Exit fullscreen mode

In this program, we use the sheet.cell(row, column) method to directly access the cell's value without iterating through the rows. The row and column arguments specify the row and column indices (1-based) of the cell you want to read.

This approach is useful when you need to read specific cells in the spreadsheet, and it's especially handy for data-driven testing, where you can extract data from specific cells and use it in your Selenium test scripts.

write a program How to send multiple sets of Data from Excel Sheet using Apache POI API

To send multiple sets of data from an Excel sheet using the Apache POI API in Selenium with Python, you can create a data-driven test script that reads data from an Excel file and uses it to perform actions in your Selenium test. Here's an example:

Install Apache POI:
If you haven't already, download the Apache POI library (HSSF for .xls or XSSF for .xlsx) and add it to your Java project's classpath. For this example, we'll use XSSF for .xlsx files.

Create an Excel File:
Create an Excel file (e.g., "test_data.xlsx") with your test data. For this example, create a simple Excel file with the following data:

| Test Case | Input Data | Expected Result |
| TC001     | Input1    | Expected1       |
| TC002     | Input2    | Expected2       |
| TC003     | Input3    | Expected3       |
Enter fullscreen mode Exit fullscreen mode

Selenium Python Program:
Here's a Python program that uses Apache POI (specifically, XSSF) to read data from the Excel file and perform actions based on that data in Selenium.

from openpyxl import load_workbook
from selenium import webdriver

# Load the Excel file
workbook = load_workbook("test_data.xlsx")

# Select the desired sheet (e.g., "Sheet1")
sheet = workbook["Sheet1"]

# Initialize the WebDriver
driver = webdriver.Chrome()
driver.get("http://your-website-url.com")

# Iterate through the rows of the Excel file
for row in sheet.iter_rows(min_row=2, values_only=True):
    test_case_id, input_data, expected_result = row

    # Perform actions based on the data
    input_element = driver.find_element(By.ID, "inputElementId")
    input_element.clear()
    input_element.send_keys(input_data)
    driver.find_element(By.ID, "submitButtonId").click()

    # Validate the result
    actual_result = driver.find_element(By.ID, "resultElementId").text
    if actual_result == expected_result:
        print(f"Test Case {test_case_id} Passed")
    else:
        print(f"Test Case {test_case_id} Failed")

# Close the WebDriver
driver.quit()

# Close the Excel file
workbook.close()
Enter fullscreen mode Exit fullscreen mode

Run the Program:
Save the Python program to a file (e.g., "data_driven_test.py") and execute it using Python:

Output:
When you run the program, it will read the data from the Excel file and perform actions in your Selenium test based on that data. The output will display whether each test case passed or failed based on the expected result.

This program demonstrates how to read multiple sets of data from an Excel file and use them in a data-driven testing framework with Selenium. It's useful for running the same test script with different sets of data, making your testing process more efficient and comprehensive.

Create an Excel workbook named "data_driven_tests.xlsx" with two sheets

"TestCases" - This sheet will contain test cases, each with a test case ID, action (e.g., "Login," "Search," "Logout"), and any additional data required for the action.
"Results" - This sheet will be initially empty and will be used to store the test results. in selenium python with example and output

Creating an Excel workbook with two sheets using the openpyxl library in Python can be done as follows:

import openpyxl

# Create a new workbook
workbook = openpyxl.Workbook()

# Rename the default sheet to "TestCases"
test_cases_sheet = workbook.active
test_cases_sheet.title = "TestCases"

# Create the "Results" sheet
results_sheet = workbook.create_sheet("Results")

# Add headers to the "TestCases" sheet
test_cases_sheet["A1"] = "Test Case ID"
test_cases_sheet["B1"] = "Action"
test_cases_sheet["C1"] = "Additional Data"

# Save the workbook to a file
workbook.save("data_driven_tests.xlsx")

# Close the workbook
workbook.close()
Enter fullscreen mode Exit fullscreen mode

This script will create an Excel workbook with two sheets, "TestCases" and "Results." It also adds headers to the "TestCases" sheet. The resulting Excel file, "data_driven_tests.xlsx," will have the desired structure.

You can then proceed to add test cases and results to the respective sheets in your Selenium test script.

write a program Python script that uses Apache POI (openpyxl) and Selenium to perform the following tasks

Read test cases from the "TestCases" sheet.
For each test case, execute the specified action on a sample website (you can use any website for this assignment).
Capture the results (e.g., pass or fail) of each test case.
Write the test results (test case ID, action, result) to the "Results" sheet. in selenium python with example and output

Below is a Python script that uses Apache POI (openpyxl) and Selenium to read test cases from the "TestCases" sheet, execute actions on a sample website, capture the results, and write the test results to the "Results" sheet in an Excel workbook. Make sure you've created the "data_driven_tests.xlsx" Excel file with the "TestCases" and "Results" sheets as mentioned in the previous answer.

Please note that you need to install the openpyxl library and have a Selenium WebDriver set up.

Excel Sheets:

TestCases Sheet (Before Execution):

| Test Case | Action | Additional Data |
| TC001     | Login  | user1           |
| TC002     | Search | query1          |
| TC003     | Logout |                |
Enter fullscreen mode Exit fullscreen mode

Results Sheet (Before Execution):


| Test Case | Action | Result |
Enter fullscreen mode Exit fullscreen mode
import openpyxl
from selenium import webdriver

# Load the Excel workbook
workbook = openpyxl.load_workbook("data_driven_tests.xlsx")

# Select the "TestCases" sheet
test_cases_sheet = workbook["TestCases"]

# Initialize the WebDriver
driver = webdriver.Chrome()

# Iterate through the rows of the "TestCases" sheet
for row in test_cases_sheet.iter_rows(min_row=2, values_only=True):
    test_case_id, action, additional_data = row

    # Sample website URL (replace with your website)
    website_url = "http://example.com"

    # Initialize the result as "Failed" by default
    result = "Failed"

    try:
        # Perform actions based on the specified action
        if action == "Login":
            # Implement the login action here
            # For example, fill in username and password fields and click the login button
            # Replace these actions with the actual Selenium code for your website
            driver.get(website_url)
            driver.find_element_by_id("username").send_keys(additional_data)
            driver.find_element_by_id("password").send_keys("password")
            driver.find_element_by_id("loginButton").click()

            # Add your validation logic here to determine the test result (e.g., check if login was successful)
            if "Logged in" in driver.page_source:
                result = "Passed"

===========================OR================================

# Assuming there's a welcome message displayed on the page after a successful login
welcome_message = driver.find_element(By.ID, "welcomeMessage").text

# Check if the welcome message is as expected
expected_message = "Welcome, user1!"
if welcome_message == expected_message:
    result = "Passed"
else:
    result = "Failed"



=============================================================
        elif action == "Search":
            # Implement the search action here
            # Replace these actions with the actual Selenium code for your website
            # Assume additional_data is the search query
            driver.get(website_url)
            driver.find_element_by_id("searchInput").send_keys(additional_data)
            driver.find_element_by_id("searchButton").click()

            # Add your validation logic here to determine the test result (e.g., check search results)
            if "Search results found" in driver.page_source:
                result = "Passed"
        elif action == "Logout":
            # Implement the logout action here
            # Replace these actions with the actual Selenium code for your website
            driver.get(website_url)
            driver.find_element_by_id("logoutButton").click()

            # Add your validation logic here to determine the test result (e.g., check if logout was successful)
            if "Logged out" in driver.page_source:
                result = "Passed"
        else:
            print(f"Unsupported action: {action}")

    except Exception as e:
        print(f"Error in test case {test_case_id}: {str(e)}")

    # Select the "Results" sheet to write the test results
    results_sheet = workbook["Results"]

    # Write the test results to the "Results" sheet
    results_sheet.append([test_case_id, action, result])

# Save the Excel workbook
workbook.save("data_driven_tests.xlsx")

# Close the Excel workbook and the WebDriver
workbook.close()
driver.quit()
Enter fullscreen mode Exit fullscreen mode

This script reads test cases from the "TestCases" sheet, performs actions on a sample website, captures the results, and writes the test results (test case ID, action, result) to the "Results" sheet in the Excel workbook.

Remember to replace the sample website URL, element locators, and validation logic with the actual values and logic for your specific website and test scenarios.

After running the script, the "Results" sheet in the "data_driven_tests.xlsx" Excel file will contain the test results, indicating whether each test case passed or failed.
Excel Sheets:

TestCases Sheet (Before Execution):

| Test Case | Action | Additional Data |
| TC001 | Login | user1 |
| TC002 | Search | query1 |
| TC003 | Logout | |
Results Sheet (Before Execution):

| Test Case | Action | Result |
Enter fullscreen mode Exit fullscreen mode

Results Sheet (After Execution):

| Test Case | Action | Result |
| TC001     | Login  | Passed |
| TC002     | Search | Passed |
| TC003     | Logout | Passed |
Enter fullscreen mode Exit fullscreen mode

After running the program, the "Results" sheet will contain the test results, indicating that all three test cases (Login, Search, and Logout) passed. The actual web page content checks and validation logic may vary depending on the website being tested.

write a program Python script Implement error handling for each test case to capture exceptions or unexpected behavior during test execution. in selenium python with example and output

Implementing error handling is crucial in any automated testing framework to capture exceptions or unexpected behavior during test execution. In Selenium with Python, you can use try-except blocks to handle exceptions. Here's an example of a Python script that includes error handling for each test case:

import openpyxl
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException, TimeoutException

# Load the Excel workbook
workbook = openpyxl.load_workbook("data_driven_tests.xlsx")

# Select the "TestCases" sheet
test_cases_sheet = workbook["TestCases"]

# Initialize the WebDriver
driver = webdriver.Chrome()

# Iterate through the rows of the "TestCases" sheet
for row in test_cases_sheet.iter_rows(min_row=2, values_only=True):
    test_case_id, action, additional_data = row

    # Sample website URL (replace with your website)
    website_url = "http://example.com"

    # Initialize the result as "Failed" by default
    result = "Failed"
    error_message = ""

    try:
        # Perform actions based on the specified action
        if action == "Login":
            # Implement the login action here
            driver.get(website_url)
            driver.find_element_by_id("username").send_keys(additional_data)
            driver.find_element_by_id("password").send_keys("password")
            driver.find_element_by_id("loginButton").click()

            # Add your validation logic here to determine the test result (e.g., check if login was successful)
            if "Logged in" in driver.page_source:
                result = "Passed"
        elif action == "Search":
            # Implement the search action here
            driver.get(website_url)
            driver.find_element_by_id("searchInput").send_keys(additional_data)
            driver.find_element_by_id("searchButton").click()

            # Add your validation logic here to determine the test result (e.g., check search results)
            if "Search results found" in driver.page_source:
                result = "Passed"
        elif action == "Logout":
            # Implement the logout action here
            driver.get(website_url)
            driver.find_element_by_id("logoutButton").click()

            # Add your validation logic here to determine the test result (e.g., check if logout was successful)
            if "Logged out" in driver.page_source:
                result = "Passed"
        else:
            error_message = f"Unsupported action: {action}"

    except NoSuchElementException as e:
        error_message = f"Element not found: {str(e)}"
    except TimeoutException as e:
        error_message = f"Timeout exception: {str(e)}"
    except Exception as e:
        error_message = f"Error in test case: {str(e)}"

    if error_message:
        result = "Failed"

    # Select the "Results" sheet to write the test results
    results_sheet = workbook["Results"]

    # Write the test results to the "Results" sheet
    results_sheet.append([test_case_id, action, result, error_message])

# Save the Excel workbook
workbook.save("data_driven_tests.xlsx")

# Close the Excel workbook and the WebDriver
workbook.close()
driver.quit()
Enter fullscreen mode Exit fullscreen mode

This modified script includes error handling using try-except blocks. It captures exceptions such as NoSuchElementException, TimeoutException, and general exceptions. If an exception occurs, the test result is marked as "Failed," and the error message is recorded in the Excel file.

The "Results" sheet now contains test results and error messages, allowing you to investigate and diagnose any issues that may occur during test execution.

write a program Python script implement error handling for each test case to capture exceptions or unexpected behavior during test execution.

Provide detailed logging for each test case, including success and failure information.
Use a separate configuration sheet to store website URLs, locators, and other configuration data.
Handle different types of actions (e.g., login, search, form submission) and data input based on the action type.in selenium python with example and output

implement error handling, provide detailed logging, use a separate configuration sheet, handle different types of actions, and capture configuration data, you can create a more comprehensive data-driven testing framework. Below is a Python script that demonstrates these features.

Here's the example script:

import openpyxl
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException, TimeoutException
import logging

# Create a logger
logging.basicConfig(filename='test.log', level=logging.INFO)
logger = logging.getLogger()

# Load the Excel workbook
workbook = openpyxl.load_workbook("data_driven_tests.xlsx")

# Select the "TestCases" sheet
test_cases_sheet = workbook["TestCases"]

# Select the "Config" sheet
config_sheet = workbook["Config"]

# Read configuration data from the "Config" sheet
config_data = {}
for row in config_sheet.iter_rows(min_row=2, values_only=True):
    config_name, config_value = row
    config_data[config_name] = config_value

# Initialize the WebDriver
driver = webdriver.Chrome()

# Iterate through the rows of the "TestCases" sheet
for row in test_cases_sheet.iter_rows(min_row=2, values_only=True):
    test_case_id, action, additional_data = row

    # Initialize the result as "Failed" by default
    result = "Failed"
    error_message = ""

    try:
        # Perform actions based on the specified action
        if action == "Login":
            # Implement the login action here
            website_url = config_data.get("login_url", "")
            driver.get(website_url)
            username_locator = config_data.get("username_locator", "username")
            password_locator = config_data.get("password_locator", "password")
            login_button_locator = config_data.get("login_button_locator", "loginButton")

            driver.find_element_by_id(username_locator).send_keys(additional_data)
            driver.find_element_by_id(password_locator).send_keys("password")
            driver.find_element_by_id(login_button_locator).click()

            # Add your validation logic here to determine the test result (e.g., check if login was successful)
            if "Logged in" in driver.page_source:
                result = "Passed"
        elif action == "Search":
            # Implement the search action here
            website_url = config_data.get("search_url", "")
            driver.get(website_url)
            search_input_locator = config_data.get("search_input_locator", "searchInput")
            search_button_locator = config_data.get("search_button_locator", "searchButton")

            driver.find_element_by_id(search_input_locator).send_keys(additional_data)
            driver.find_element_by_id(search_button_locator).click()

            # Add your validation logic here to determine the test result (e.g., check search results)
            if "Search results found" in driver.page_source:
                result = "Passed"
        elif action == "Logout":
            # Implement the logout action here
            website_url = config_data.get("logout_url", "")
            driver.get(website_url)
            logout_button_locator = config_data.get("logout_button_locator", "logoutButton")

            driver.find_element_by_id(logout_button_locator).click()

            # Add your validation logic here to determine the test result (e.g., check if logout was successful)
            if "Logged out" in driver.page_source:
                result = "Passed"
        else:
            error_message = f"Unsupported action: {action}"

    except NoSuchElementException as e:
        error_message = f"Element not found: {str(e)}"
        logger.error(f"Error in test case {test_case_id}: {error_message}")
    except TimeoutException as e:
        error_message = f"Timeout exception: {str(e)}"
        logger.error(f"Error in test case {test_case_id}: {error_message}")
    except Exception as e:
        error_message = f"Error in test case {test_case_id}: {str(e)}"
        logger.error(f"Error in test case {test_case_id}: {error_message}")

    if error_message:
        result = "Failed"

    # Select the "Results" sheet to write the test results
    results_sheet = workbook["Results"]

    # Write the test results to the "Results" sheet
    results_sheet.append([test_case_id, action, result, error_message])

# Save the Excel workbook
workbook.save("data_driven_tests.xlsx")

# Close the Excel workbook and the WebDriver
workbook.close()
driver.quit()
Enter fullscreen mode Exit fullscreen mode

In this script:

We create a logger to capture detailed information about test case execution, including both success and failure information. The log is saved in a file named "test.log."

The script reads configuration data from the "Config" sheet, including URLs and locators for various actions. This makes the script more modular and allows for easy configuration changes without modifying the script.

Error handling is implemented using try-except blocks for each test case. Any exceptions that occur are logged with error messages.

The script captures different types of actions based on the "action" column in the "TestCases" sheet.

The "Results" sheet records both test results (Pass/Fail) and any error messages.

When you run this script, it performs data-driven testing with error handling, detailed logging, and configuration-driven actions, providing a robust and maintainable approach for automated testing. The log file "test.log" will contain information about each test case execution, including both successful and failed test cases.

write a program Python script When the script is executed, it should read test cases from the "TestCases" sheet, perform the specified actions on the website, and write the results to the "Results" sheet.

The "Results" sheet should provide clear information about which test cases passed and which failed..in selenium python with example and output

Certainly! Here's a Python script that reads test cases from the "TestCases" sheet, performs specified actions on a website, and writes the results to the "Results" sheet, clearly indicating which test cases passed and which failed:

import openpyxl
from selenium import webdriver

# Load the Excel workbook
workbook = openpyxl.load_workbook("data_driven_tests.xlsx")

# Select the "TestCases" sheet
test_cases_sheet = workbook["TestCases"]

# Initialize the WebDriver
driver = webdriver.Chrome()

# Select the "Results" sheet
results_sheet = workbook["Results"]

# Initialize a list to store test results
test_results = []

# Iterate through the rows of the "TestCases" sheet
for row in test_cases_sheet.iter_rows(min_row=2, values_only=True):
    test_case_id, action, additional_data = row

    # Initialize the result as "Failed" by default
    result = "Failed"

    try:
        # Perform actions based on the specified action
        if action == "Login":
            # Implement the login action here (replace with your own logic)
            driver.get("https://example.com/login")
            # ...

        elif action == "Search":
            # Implement the search action here (replace with your own logic)
            driver.get("https://example.com/search")
            # ...

        # Add more cases for different actions

        # If the test case execution reaches here, it's considered "Passed"
        result = "Passed"

    except Exception as e:
        # If an exception occurs, log the error and set the result to "Failed"
        print(f"Test Case {test_case_id} failed: {str(e)}")

    finally:
        # Append the test result to the list
        test_results.append([test_case_id, action, result])

# Write the test results to the "Results" sheet
for result_row in test_results:
    results_sheet.append(result_row)

# Save the Excel workbook
workbook.save("data_driven_tests.xlsx")

# Close the Excel workbook and the WebDriver
workbook.close()
driver.quit()
Enter fullscreen mode Exit fullscreen mode

In this script:

We load the Excel workbook and select the "TestCases" sheet to read the test cases.

The WebDriver is initialized (Chrome in this example).

Test results are stored in the test_results list, with each result indicating the test case ID, action, and result (either "Passed" or "Failed").

The script iterates through the test cases, performs actions, and captures exceptions. If an exception occurs, it sets the result to "Failed."

The test results are then written to the "Results" sheet, clearly indicating which test cases passed and which failed.

After running this script, you can open the "Results" sheet in the "data_driven_tests.xlsx" Excel file to view the pass/fail status of each test case. The Excel file will provide clear information about the test case results.

Top comments (0)