Showing posts with label software testing tutorial. Show all posts
Showing posts with label software testing tutorial. Show all posts

February 20, 2023

SelectorsHub Tutorial - SelectorsHub XPath | How to use SelectorsHub | CSS SelectorsHub | How to install SelectorsHub

Summary: SelectorsHub is a tool that helps to find the correct and unique locators for web elements in automated testing scripts. SelectorsHub tool generates and verifies locators such as XPath, CSS selector and playwright selectors. SelectorsHub XPath tool is free, more accurate and user-friendly than other tools like browser developer tools. It works with various browsers, and the installation process is easy. To use SelectorsHub, you need to open the web page, right-click on the web element, click "Inspect" and then open SelectorsHub to see the suggested selectors. You can copy the desired selector and paste it in your test script for use as locators in Selenium etc. SelectorsHub also provides an attribute filter to search for selectors with specific attributes.

Welcome to this SelectorsHub tutorial. In this blog post, I will cover the basics about SelectorsHub, including what it is, how to install it and how to use it. This post is part of my SelectorsHub course, which aims at helping you learn everything there is to know about SelectorsHub. You can view this SelectorsHub tutorial below or read on.

What is SelectorsHub? SelectorsHub is a free tool that helps you find the correct and unique locators for your web elements. Whether you use Selenium Webdriver or any other tool, SelectorsHub is the software testing tool for locating web elements accurately and efficiently.
You can use SelectorsHub XPath or CSS SelectorsHub to get the locators you need for your automation testing script. Unlike other tools, such as the developer tools you get in your browser, SelectorsHub is more accurate and user-friendly. It generates and verifies XPath, CSS selector, and playwright selectors, jQuery and other selectors.

How to Install SelectorsHub: The installation process for SelectorsHub is straightforward. All you need to do is choose your browser and follow simple steps for SelectorsHub install. For example, for Google Chrome users, visit the Chrome web store and search for SelectorsHub. Click "Add to Chrome" to download the extension.  After adding SelectorsHub to your browser, restart it. You should now see the SelectorsHub icon in your extensions. Open any web page, right-click on any element and select "Inspect." On the right side of the developer tools window, you should see SelectorsHub. SelectorsHub is also linked on the SelectorsHub website, where you can find SelectorsHub install links for all major browsers.

How to use SelectorsHub: SelectorsHub usage is easy. All you need to do is open the web page you want to test, right-click on the web element and then click on "Inspect." From here, open SelectorsHub, and it will show you the available selectors. You can copy the desired selector and paste it into your script as locators in Selenium WebDriver.

SelectorsHub Features: Here are some of the basic SelectorsHub features:
1) Suggested Selectors: SelectorsHub shows you the suggested selectors. For example, you can see the suggested selectors for the Google search box, including a relative CSS selector and a relative XPath.
2) Copying Selectors: You can copy any of the selectors shown and paste them into your automation testing script.
3) User-Friendly Interface: SelectorsHub has a user-friendly interface that makes it easy to find the correct and unique locators.

Conclusion: SelectorsHub tool is excellent for anyone who needs to locate web elements accurately and efficiently. It is easy to install, user-friendly and provides accurate selectors. With SelectorsHub, you can significantly speed up your automation testing and save time in your web development projects.

Want to learn more? Get free SelectorsHub training with the SelectorsHub free full course.

Note: With this SelectorsHub tutorial, you can learn about SelectorsHub xpath, how to use selectorshub to find locators in Selenium, CSS selectorshub and how to install selectorshub to find correct locators in Selenium Webdriver.

May 09, 2021

Orthogonal Array Testing in Software Engineering | Orthogonal Array Testing Example

Welcome to this post on Orthogonal Array Testing in software engineering. Orthogonal array testing is black box testing. When you have a large number of input combinations, orthogonal array testing gives very few test cases. View the below tutorial or read on...

What is Orthogonal Array? It is a table. The columns (a.k.a. factors) represent the independent variables. The rows (a.k.a. experiments or runs) represent the variables' combinations. The orthogonal array testing example below is for a web page with three sections - TOP, LEFT and RIGHT. Note that the orthogonal array has only 4 test cases to run for 8 input combinations.

What is Orthogonal Array Testing? The Orthogonal Array Technique has the following steps:

  1. Identify the independent variables. Put them as column headers in the table.
  2. For each independent variable, identify the number of possible values.
  3. Search an Orthogonal Array with the smallest number of rows in orthogonal array design of experiments. I have explained this step here.
  4. Put the independent variable values in the Orthogonal Array cells. If any cells are still blank, repeat the values in them.
  5. Test each row in the table.

In the example below, there are 3 independent variables (put as column headers). Variable A has 2 possible values, A1 and A2. Variable B has 3 possible values, B1, B2 and B3. Variable C has 3 possible values, C1, C2 and C3. The input combinations are therefore 2 * 3 * 3, which is 18. The smallest number of rows can be found in this orthogonal array. Using the above orthogonal array technique, the table should look like below. Instead of testing 18 input combinations, orthogonal array gives only 9 test cases to run.

Note: 1) Since variable A has only 2 values, they are used to complete the first column.
2) Since there are only 3 variables, the 4th column is not used.

Want to learn the above Orthogonal Array Testing examples in detail? Please view my Orthogonal Array Testing tutorial

Donate USD 1$ to me on PayPal

Note: Links are only welcome from supporting organizations or individuals. Other comments with links will be deleted. Thank you.

April 29, 2021

Mutation Testing in Software Testing | Mutation Analysis | White Box Testing

After being occupied with some commitments for about two months, I finally got time to write the next article 😊. This post is on Mutation Testing, a white box testing, to test program code. Mutation testing is also useful for test automation code, databases, software models and other artifacts in software engineering. View the below tutorial or read on...

What is Mutation Testing in software testing? Basically, in Mutation Testing, you make a change (a mutation) to your program and run your tests with test data. Mutation Testing finds if your existing tests and test data are useful or not. Using Mutation Testing, you could know which sections of your program are tested poorly. Also, you could identify your tests that never find any mutants (changed copies of your program). In the example below, the program on the left is the original program and the program on the right is it's mutant.

Mutation Testing process (Mutation Analysis)

1) You test your original program with all your tests and test data. If any test fails, you need to fix your program or that test or it's test data. 

2) Once your program passes all the tests, you create mutants by using any mutation operator (e.g delete a statement, duplicate a statement, exchange operators etc.) and test your mutants. Each test run on any mutant should ideally fail, because a mutant is a changed copy of your program. 

3) If a test run on any mutant passes, you should find out the reason (e.g. the mutated code is not run or the mutant is functionally "equivalent" to your program). In order to find more mutants, you need to update your existing tests (or test data) and/ or write new tests (with test data). Also, if you update your test set or test data, you need to repeat the above process from step 1).

Want to learn Mutation Testing more? Like Mutation Analysis in detail, Mutation Score and Mutation Testing assumptions? Then, please view the complete Mutation Testing tutorial. Thank you.

February 28, 2021

Data Flow Testing in Software Testing | White Box Testing


This post is on Data Flow Testing. What is data flow testing? Data flow testing in software testing is white box testing. Data flow testing is also a structured testing methodology, based on your program's internal structure. Data flow testing focuses on variables' definition and use. A variable is a memory location that can store a value. A variable's value can be used in a condition or a calculation. Now, in a program, it is possible for the developer to use a variable that doesn't exist or update a variable's value by error. In data flow testing, you examine the variables in your program. View my Data Flow Testing tutorial for more details or read on.
Data flow testing strategies in software testing include:
1) Define Use Testing - DU Testing has some rules and metrics. It tests the paths of the Control Flow Graph (view my Path Testing tutorial to learn about Control Flow Graph) that have a variable defined or used.

2) Program Slices - Program slices strategy divides the program into executable sections, for a variable. You could then test a single program slice independently, for that variable.

Let us see the data flow testing example. This example program computes the Sum of some numbers. Here is the Control Flow Graph when the variable n gets a value of 0 (in Node 4).

If the variable n has a non-zero value, a different path is taken in the Control Flow Graph. The reason is that the while loop is also run. Here is the Control Flow Graph when the variable n gets a value of say, 100, the first time (in Node 4) and 0 the second time (in Node 8).
Let us now learn about Define Use Testing. A particular node in the Control Flow Graph can be either a Define Node or Use Node. A variable is given a value in a Define Node. Examples of Define Nodes are Node 2 (the variable i is given a value), Node 3 (the variable sum is given a value), Node 4 (the variable n is given a value) or Node 8 (again, the variable n is given a value). A variable's value is used in a Use Node. Examples of Use Nodes are Node 6 (the value of variable sum is used; also the value of variable n is used) or Node 7 (the value of variable i is used in the computation) or Node 10 (the value of variable i is used; also the value of variable sum is used in the print statement). Learn about P-use (Predicate Use) and C-use (Computation Use) here. In Define Use Testing, you should identify the Define Use nodes for each variable. I have explained how to find the Define nodes and Use nodes for variables i, n and sum here. In Define Use Testing, you should identify some paths according to your chosen Define Use Testing Metrics and test those paths to find bugs.
 
Moving on to Program Slices. This data flow testing strategy is useful when your program is large in size. You could identify a program slice (a set of statements) for a single variable, up to any statement in your program. I have explained how to identify program slices for variables i, n and sum here.

Using both Define Use Testing and Program Slices data flow testing techniques, here are four Define Use Paths (pink table below) to test for variable n. In Data Flow Testing, you could test these paths. Similarly, you could identify the paths to test for variable i and variable sum and test them too.

Want to learn Data Flow Testing in detail? Learn Data Flow Testing Metrics? Then please view the complete Data Flow Testing with Example Tutorial. Thank you.

January 10, 2021

Path Testing in Software Testing with Example | Triangle Problem

This post explains Path Testing in software testing. Path testing is one of the test design techniques. Path testing is a structured testing methodology, meaning it is based on mathematics. Path testing is white box testing and complementary to other software testing methodologies like requirements based testing. View my Path Testing tutorial to understand path testing. Then read on.
 
In order to use path testing techniques, you should know about the Control Flow Graph, which represents the program or the algorithm to be tested. Here is the Control Flow Graph for the Triangle Problem example below. In this Control Flow Graph, 1 is the Entry Node and 10 is the Exit node. The nodes 1 through 10 represent the Steps below. The directional arrows e.g. Node 1 to Node 2 represent the control flow between the Steps. The directional arrows are called Edges. Using the Control Flow Graph, you can compute the Cyclomatic Complexity, which is E - N + 2, where E is the number of Edges and N is the number of Nodes. In this Control Flow Graph example, Cyclomatic Complexity is 12 - 10 + 2 = 4.
 
The Triangle Problem is to find out the type of the triangle, given its' three sides. Here is the algorithm for the Triangle Problem.
 
In path testing for triangle problem, there are four basis (independent) paths of algorithm execution, which you need to test with test data.
  • Not a Triangle: Node1 > Node2 > Node3 > Node10
  • Equilateral Triangle: Node1 > Node2 > Node4 > Node5 > Node10
  • Isosceles Triangle: Node1 > Node2 > Node4 > Node6 > Node7 > Node10
  • Scalene Triangle: Node1 > Node2 > Node4 > Node6 > Node8 > Node9 > Node10
Want to learn Path testing with example explained in detail? Want to learn the Path Testing process? Then, please view my Path Testing in Software Testing tutorial. Thank you.

August 09, 2020

Selenium Python Tutorial 14 | Selenium Python Unittest Framework with POM | Selenium Unit Testing

This is the next tutorial in the Selenium Python Tutorials for Beginners. It deals with Python Automation Testing with Selenium WebDriver Python. This Selenium Python beginner tutorial deals with the Selenium Python Unittest framework and Selenium unit testing. First, view the Selenium Python Unit Test Tutorial. Then read on.

Here is my Selenium Python example, which is based on the example that I showed in my Selenium Python tutorial 13. This Page Object Model (POM) based Selenium Python example uses the Python unit test framework to run the test methods in a test class. I put explanations in the comments within the code (lines starting with #).

# Test_Cases>WikipediaTestClass1.py
# Selenium WebDriver Python coding
# Import unittest library for working with Selenium Unit Testing Python.
import unittest
from selenium import webdriver
# Import the page object files in the Pages directory.
# The POM files are MainPage.py and EnglishPage.py. Their code is in Selenium Python tutorial 13.
from Pages.MainPage import MainPage
from Pages.EnglishPage import EnglishPage

class WikipediaTestClass1(unittest.TestCase):
    exec_path = r"E:\Training\SeleniumPython\Downloads\geckodriver-v0.26.0-win32\geckodriver.exe"
    base_URL = "https://www.wikipedia.org/"

    # First independent test method to test the main page
    def test_main_page(self):
        driver = webdriver.Firefox(executable_path=self.exec_path)
        driver.get(self.base_URL)
        mp = MainPage(driver)
        mp.test_title()

    # Second independent test method to test the english page
    def test_english_page(self):
        driver = webdriver.Firefox(executable_path=self.exec_path)
        driver.get(self.base_URL)
        mp = MainPage(driver)
        mp.click_english_link()
        ep = EnglishPage(driver)
        ep.search_text()

# Run all test methods using the unit test library.
# In PyCharm, click the green arrow next to this if statement and then click Run 'WikipediaTestClass1'.
if __name__ == "__main__": unittest.main()

Next, in this Selenium WebDriver Python tutorial, let us see the Selenium Python example to skip test methods using Selenium Python. I modified the above Python script to skip test methods.

# Test_Cases>WikipediaTestClass2.py
# Selenium WebDriver Python coding
import unittest
from selenium import webdriver
from Pages.MainPage import MainPage
from Pages.EnglishPage import EnglishPage

class WikipediaTestClass2(unittest.TestCase):
    # run_all_test_cases variable is used to skip unit tests conditionally.
    run_all_test_cases = False
    exec_path = r"E:\Training\SeleniumPython\Downloads\geckodriver-v0.26.0-win32\geckodriver.exe"
    base_URL = "https://www.wikipedia.org/"

    # If you want to skip unit test with condition, use the skipIf unit test annotation.
    @unittest.skipIf(run_all_test_cases==False, "This is a medium priority test case.")
    def test_main_page(self):
        driver = webdriver.Firefox(executable_path=self.exec_path)
        driver.get(self.base_URL)
        mp = MainPage(driver)
        mp.test_title()

    # If you want to skip unit test, uncomment the unit test annotation.
 # @unittest.SkipTest
    def test_english_page(self):
        driver = webdriver.Firefox(executable_path=self.exec_path)
        driver.get(self.base_URL)
        mp = MainPage(driver)
        mp.click_english_link()
        ep = EnglishPage(driver)
        ep.search_text()

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

Finally, let us see the Selenium Python example with unit testing setup method and unit testing teardown method. I added these unit test special methods, the unit testing set up method and and unit testing tear down method to the above Python script.

# Test_Cases>WikipediaTestClass3.py
# Selenium WebDriver Python coding
import unittest
from selenium import webdriver
from Pages.MainPage import MainPage
from Pages.EnglishPage import EnglishPage

class WikipediaTestClass3(unittest.TestCase):
    exec_path = r"E:\Training\SeleniumPython\Downloads\geckodriver-v0.26.0-win32\geckodriver.exe"
    base_URL = "https://www.wikipedia.org/"
    driver = webdriver.Firefox(executable_path=exec_path)

    # unit test setUp method runs before every test method. 
    #  Notice the @classmethod unit test annotation.
    @classmethod
    def setUp(self):
        print("This method runs before every test method.")
        self.driver.get(self.base_URL)

    # unit test tearDown method runs after every test method. 
    #  Notice the @classmethod unit test annotation.
    @classmethod
    def tearDown(self):
        print ("This method runs after every test method.")

    def test_main_page(self):
        mp = MainPage(self.driver)
        mp.test_title()

    def test_english_page(self):
        mp = MainPage(self.driver)
        mp.click_english_link()
        ep = EnglishPage(self.driver)
        ep.search_text()

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

Want to see the Python unit test library run the above Selenium Python examples? Then view my Python Selenium UnitTest Tutorial and Selenium Python Unit Testing with POM Tutorial. Thank you.

August 02, 2020

Selenium Python Tutorial 13 | Framework | Selenium Python Page Object Model | Python selenium POM

Moving on to the next tutorial in the Selenium Python Tutorials for Beginners. It deals with Python Automation Testing with Selenium WebDriver Python. This Selenium Python beginner tutorial explains Selenium Python Page Object Model, also known as the POM framework. Not using the Selenium Python POM framework results in lower Python code readability and code duplicity. We can implement Python Selenium POM by creating separate Python files for the web page and the test logic. First, view the Selenium Python Page Object Model Tutorial Then read on.

Selenium Python POM implementation has the following steps:
  • Create separate directories for web pages and test cases. Optionally, create separate directories for browser drivers, logs and screenshots.
  • In the web pages directory, create a separate Python file for each web page. This Python file should contain the code for web page operations, web page locators and title etc.
  • In the test cases directory, create a separate Python file for each test case. This Python file should contain only the test logic, which consists of test steps and expected results' validations.
Here is my Selenium Python Page Object example. This is based on the Selenium Python example that I showed in the Selenium Python tutorial 1. I created the directories Test_Cases and Pages by right clicking the project in PyCharm IDE > New > Directory. Then, I created the Python files within the relevant directories by select the directory > right click > New > Python File. Within the Python code, I put explanations in the comments within the code (lines or phrases starting with #).

# Test_Cases>WikipediaTest1.py
# Selenium WebDriver Python coding
from selenium import webdriver
from Pages.MainPage import MainPage
from Pages.EnglishPage import EnglishPage
exec_path = r"E:\Training\SeleniumPython\Downloads\geckodriver-v0.26.0-win32\geckodriver.exe"
driver = webdriver.Firefox(executable_path=exec_path)
base_URL = "https://www.wikipedia.org"

def set_up():
    driver.get(base_URL)

# Test logic containing the test steps and expected results' validation
def test_main_page():
    mp = MainPage(driver)
    mp.test_title()
    mp.click_english_link()

# Test automation logic (test steps and expected results' validation)
def test_english_page():
    ep = EnglishPage(driver)
    ep.search_text()

set_up()
test_main_page()
test_english_page()

# Pages>MainPage.py
# Selenium WebDriver Python coding
from selenium.webdriver.common.by import By
# Import statements for Explicit Wait or WebDriverWait Python
from selenium.webdriver.support.ui import WebDriverWait as W
from selenium.webdriver.support import expected_conditions as E

class MainPage():
    # Put the title and web page locators.
    title = "Wikipedia"
    english_partial_link_text = "English"
    wait_time_out = 5 # for explicit wait

    # init method will be executed automatically when the MainPage object is created.
    def __init__(self, drv):
        self.drv = drv
        self.wait_variable = W(self.drv, self.wait_time_out)

    # Now, add methods for automation test logic.
    # test_title is a web page operation in the MainPage for expected result validation.
    def test_title(self):
        assert self.title in self.drv.title

    # click_english_link is also a web page operation in the MainPage.
    def click_english_link(self):
        self.wait_variable.until(E.element_to_be_clickable((By.PARTIAL_LINK_TEXT, self.english_partial_link_text))).click() 

# Pages>EnglishPage.py
# Selenium WebDriver Python coding 
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as W
from selenium.webdriver.support import expected_conditions as E

class EnglishPage():
    # Put the web page locators and search term.
    search_id_locator = "searchInput"
    term = "Software"
    wait_time_out = 5 # for WebDriverWait Python

    # The class init method is also called the constructor.
    def __init__(self, drv):
        self.drv = drv
        self.wait_variable = W(self.drv, self.wait_time_out)

    # automation test logic
    def search_text(self):
        input_box_element = self.wait_variable.until(E.presence_of_element_located((By.ID, self.search_id_locator)))
        input_box_element.send_keys(self.term)
        input_box_element.submit()
        # Expected result validation
        self.wait_variable.until(E.title_contains(self.term))

Want to understand how the Python code above works? And how to implement logging and screenshots in the POM framework easily? Then please view my Selenium Python POM Tutorial. Thank you.


July 26, 2020

Selenium Python Tutorial 12 | Selenium python read Excel | Python selenium write to Excel | OpenPyXL

This is the next tutorial in the Selenium Python Tutorials for Beginners. It deals with Python Automation Testing with Selenium WebDriver Python. This Selenium Python beginner tutorial explains Selenium Python read Excel test data and Python Selenium write to Excel the test results. First, view the Selenium Python Excel Tutorial. Then read on.

In order to work with Selenium Python Excel, we can use the OpenPyXL library for commands to open Excel file, open a single worksheet, access a specific cell in the worksheet and save the Excel file. In the command prompt, we can use pip to install OpenPyXL as shown below:

Next, in our PyCharm project, we need to install the OpenPyXL package. We can click File > Settings > Project > Project interpreter. Then click + button, which is the Install button. It shows all the available packages. In the search text box, type openpyxl. Select openpyxl and click Install Package button. It gives the message, Package 'openpyxl' installed successfully. Click Close button.

Here is my first Selenium Python example for selenium python read Excel. This is the ExcelRead.py Python script that I showed in the Selenium Python tutorial 11. I have put explanations in the comments within the code (lines or phrases starting with #).

# Selenium WebDriver Python coding
# Import OpenPyXL to work with Python Selenium Excel.
import openpyxl as O
# Specify the Selenium Python Excel file path and file name with your computer's folder.
# Escape the backslashes. The following is an example only.
Excel_file = "E:\\Training\\SeleniumPython\\TestData\\JourneyPlanner.xlsx"
# My Excel worksheet has the columns Distance, Speed, Travel hours/ day, Expected Result - Travel days and Test result.
# You can see the Excel worksheet format in the Selenium Python tutorial 12.
Excel_worksheet = "Data1"
# Python Selenium open Excel file
wb = O.load_workbook(Excel_file)
# Python Selenium open Excel worksheet in the Excel file
ws = wb[Excel_worksheet]
row_num = ws.max_row
col_num = ws.max_column
print ("The number of rows is ", row_num, "and the number of columns is ", col_num)
row = 2 # In the Excel worksheet, the first row has headers. The test data is in the second row.
print ("distance = ", ws.cell(row, 1).value)
print ("speed = ", ws.cell(row, 2).value)
print ("Travel hours/day = ", ws.cell(row, 3).value)
print ("Expected Result = ", ws.cell(row, 4).value)

Here is my second Selenium Python example for Python Selenium write to Excel. This is the DropDownTestData.py Python script that I showed to test the Journey Planner application in the Selenium Python tutorial 4. I modified the DropDownTestData.py Selenium Python script to read test data values and use Python Selenium write to Excel.

# Selenium WebDriver Python coding
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as W
from selenium.webdriver.support import expected_conditions as E
from selenium.webdriver.support.ui import Select
import time
# Import OpenPyXL to work with Selenium Python Excel.
import openpyxl as O
exec_path = r"E:\Training\SeleniumPython\Downloads\geckodriver-v0.26.0-win32\geckodriver.exe"
URL = "https://inderpsingh.blogspot.com/2014/08/demowebapp_24.html"
Excel_file = "E:\\Training\\SeleniumPython\\TestData\\JourneyPlanner.xlsx"
# My Excel worksheet has the columns Distance, Speed, Travel hours/ day, Expected Result - Travel days and Test result. 
# You can see the Excel worksheet format in the Selenium Python tutorial 12
Excel_worksheet = "Data1"
distance_id_locator = "distance"
speed_id_locator = "speed"
time_id_locator = "hours"
calculate_css_locator = ".post-body > div:nth-child(1) > div:nth-child(1) > form:nth-child(1) > button:nth-child(20)"
result_id_locator = "result"
message_id_locator = "message"
wait_time_out = 5
driver = webdriver.Firefox(executable_path=exec_path)
driver.get(URL)
wait_variable = W(driver, wait_time_out)
driver.execute_script("window.scrollBy(0,240)", "")
distance_element=wait_variable.until(E.presence_of_element_located((By.ID, distance_id_locator)))
speed_element=wait_variable.until(E.presence_of_element_located((By.ID, speed_id_locator)))
time_element=Select(wait_variable.until(E.presence_of_element_located((By.ID, time_id_locator))))
calculate_element=wait_variable.until(E.presence_of_element_located((By.CSS_SELECTOR, calculate_css_locator)))
# The result_element gives the result if the test data is valid.
result_element = wait_variable.until(E.presence_of_element_located((By.ID, result_id_locator)))
# The message_element gives the error message if the test data is invalid.
message_element=wait_variable.until(E.presence_of_element_located((By.ID, message_id_locator)))
# Python Selenium open Excel file
wb = O.load_workbook(Excel_file)
ws = wb[Excel_worksheet]
# Run the for loop from 2 (because row 1 has headers, not the test data).
for r in range(2, ws.max_row + 1):
    d = str(ws.cell(r, 1).value)
    distance_element.clear()
    distance_element.send_keys(d)
    s = str(ws.cell(r, 2).value)
    speed_element.clear()
    speed_element.send_keys(s)
    t = str(ws.cell(r, 3).value)
    time_element.select_by_visible_text(t)
    calculate_element.click()
    time.sleep(1)
    e = str(ws.cell(r, 4).value)
    # Check if the result or error message is the same as test data in the Excel file.
    if str(e) in result_element.text or str(e) in message_element.text:
        ws.cell(r, 5).value = "Pass"
    else:
        ws.cell(r, 5).value = "Fail"
    # Python Selenium write to Excel on disk
   # The Excel file must be closed when the save and close methods run.
    wb.save(Excel_file)
    wb.close()

Want to understand how the above Selenium Python script works? Please view my Selenium Python Read Excel Write Excel Tutorial. Thank you.


July 19, 2020

Selenium Python Tutorial 11 | Selenium python Logging | Log File

Moving on to the next tutorial in the Selenium Python Tutorials for Beginners. It deals with Python Automation Testing with Selenium WebDriver Python. This Selenium Python beginner tutorial explains Python Selenium logging with import logging library. You can log multiple messages using the Selenium Python logging at multiple levels (debug, info, warning, error and critical). First, view the Selenium Python Logging Tutorial. Then read on.

 After import logging in Python 3, you can use logging.basicConfig to configure logging e.g. to log only certain levels, specify a logging format or specify the log file. Here is the first Selenium Python logging example, which is in Logs.py file in the Selenium Python tutorial 11. The explanations are in the comments within the code (lines or phrases starting with #).

# Selenium WebDriver Python coding
# import Python logging library with the alias, L
import logging as L
# Configure logging to start with severity level, DEBUG.
L.basicConfig(level=L.DEBUG)
L.debug('Debug message')
L.info('Info message')
L.warning('Warning message')
L.error('Error message')
L.critical('Critical message')

This is my Python user defined function to log messages automatically. I put it in the Utilities.py file that I showed in the Selenium Python tutorial 10.

# Selenium WebDriver Python coding
import logging as L
def log(level, message, file):
    # Configure logging to start with the INFO level, the log file and the filemode as append to log file.
    L.basicConfig(level=L.INFO, filename=file, filemode="a",
                  format="%(asctime)-12s %(levelname)s %(message)s", # log entry format
                  datefmt="%d-%m-%Y %H:%M:%S") # date time format
    if level == "INFO": L.info(message)
    if level == "WARNING": L.warning(message)
    if level == "ERROR": L.error(message)
    if level == "CRITICAL": L.critical(message)

Here is my log function called in the Checkbox.py Selenium Python example that I showed in the Selenium Python tutorial 3. The Checkbox.py Selenium Python script answers a quiz automatically until each answer is "Correct." or it runs out of checkbox combinations.

# Selenium WebDriver Python coding
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as W
from selenium.webdriver.support import expected_conditions as E
import CheckboxFunctions as C
# Import Utilities in order to call the log function.
import Utilities as U

exec_path = r"E:\Training\SeleniumPython\Downloads\geckodriver-v0.26.0-win32\geckodriver.exe"
URL = "https://inderpsingh.blogspot.com/2013/01/HTMLCSSQuiz1.html"
wait_time_out = 15
check_name_locator = "option"
# Specify the log file file path and file name with your computer's folder. Escape the backslashes.
# The following is an example only.
log_file = "E:\\Training\\SeleniumPython\\Logs\\LogCheckBoxQuiz.txt"
# Specify the log message for pass and fail.
pass_message = "Answered correctly - Question Number"
fail_message = "Answered incorrectly - Question Number"

driver = webdriver.Firefox(executable_path=exec_path)
wait = W(driver, wait_time_out)
driver.get(URL)
i = 0
while i<10:
    i += 1
    driver.execute_script("window.scrollBy(0,120)","")
    check_element_1 = wait.until(E.presence_of_element_located((By.NAME, check_name_locator + str(i) + "1")))
    check_element_2 = wait.until(E.presence_of_element_located((By.NAME, check_name_locator + str(i) + "2")))
    check_element_3 = wait.until(E.presence_of_element_located((By.NAME, check_name_locator + str(i) + "3")))
    check_element_1.click()
    check_element_2.click()
    check_element_3.click() # checkboxes 1, 2 & 3 are selected
    if C.answered(driver, i):
        # Python Selenium logging if the question is answered successfully
        U.log("INFO", pass_message + str(i), log_file)
        continue
    check_element_1.click() # checkboxes 2 & 3 are selected
    if C.answered(driver, i):
        # Python Selenium logging if the question is answered successfully
        U.log("INFO", pass_message + str(i), log_file)
        continue
    check_element_1.click()
    check_element_2.click() # checkboxes 1 & 3 are selected
    if C.answered(driver, i):
        # Python Selenium logging if the question is answered successfully
        U.log("INFO", pass_message + str(i), log_file)
        continue
    check_element_2.click()
    check_element_3.click() # checkboxes 1 & 2 are selected
    if C.answered(driver, i):
        # Python Selenium logging if the question is answered successfully
        U.log("INFO", pass_message + str(i), log_file)
        continue
    check_element_2.click() # only checkbox 1 is selected
    if C.answered(driver, i):
        # Python Selenium logging if the question is answered successfully
        U.log("INFO", pass_message + str(i), log_file)
        continue
    check_element_1.click()
    check_element_2.click() # only checkbox 2 is selected
    if C.answered(driver, i):
        # Python Selenium logging if the question is answered successfully
        U.log("INFO", pass_message + str(i), log_file)
        continue
    check_element_2.click()
    check_element_3.click()# only checkbox 3 is selected
    if C.answered(driver, i):
        # Python Selenium logging if the question is answered successfully
        U.log("INFO", pass_message + str(i), log_file)
        continue
    # Selenium Python logging if the question is still unanswered.
    U.log("ERROR", fail_message + str(i), log_file)

The above Selenium Python script calls the answered user defined function that I wrote in CheckboxFunctions.py file below.
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as W
from selenium.webdriver.support import expected_conditions as E
wait_time_out = 15
def answered(d, question_number):
    wait_variable = W(d, wait_time_out)
    answer_element = wait_variable.until(E.presence_of_element_located((By.NAME, "answer" + str(question_number))))
    if "Correct." in answer_element.get_attribute("value"):
        return True
    else:
        return False

Want to see the above Selenium Python test automation working? Please view my Selenium Python Logging Tutorial. Thank you.

July 12, 2020

Selenium Python Tutorial 10 | Selenium python Screenshot | selenium python screenshot_as_png

This is the next tutorial in the Selenium Python Tutorials for Beginners. This Selenium Python beginner tutorial explains Selenium Python screenshot or Selenium Python snapshot, meaning the image of the screen in a specific state. We may need to take a Selenium Python screenshot on failure of test case for bug reporting or on success for proof of testing. First, view the Selenium Python Screenshot Tutorial. Then read on.

Here is my Selenium Python example with a Python user defined function to take a WebDriver screenshot Python automatically. Then, I will use Python Imaging Library to modify the screenshot. The explanations are in the comments within the code (lines starting with #).

# Selenium WebDriver Python coding
# This Python file, Utilities.py, contains the WebDriver screenshot Python functions, screenshot and modify_screenshot.
import time
from PIL import Image as I

def screenshot(d):
    """Take the Selenium Python screenshot with the current date and time"""
    # Put the folder path with your computer's folder. The following folder path is an example only.
    # Escape each backslash with another backslash.
    folder = "E:\\Training\\SeleniumPython\\Screenshots\\"
    time_string = time.asctime().replace(":", " ")
    # Take Selenium Python screenshot_as_png
    file_name = folder + time_string + ".png"
    # Save Python Selenium screenshot with Selenium WebDriver save_screenshot method.
    d.save_screenshot(file_name)
   # Another Save Python Selenium screenshot with Selenium WebDriver method is get_screenshot_as_file (commented out).
    #d.get_screenshot_as_file(file_name)
    modify_screenshot(file_name)

def modify_screenshot(f):
    picture = I.open(f)
    # Modify the screenshot. Resize screenshot to another screen resolution.
    picture = picture.resize((1280, 654))
    # Modify the screenshot. Rotate screenshot by 90 degrees.
    picture = picture.transpose(I.ROTATE_90)
    # Modify the screenshot to save Selenium Python screenshot_as_jpg.
    picture = picture.convert("RGB")
    # Python strings are immutable. Create a new string for the filename.
    f_new = f.replace(".png", ".jpg")
    picture.save(f_new)

Here is my Selenium Python script, Screenshots.py that calls the Python Selenium screenshot function. Note that the screenshot user defined function calls the modify_screenshot function on it's last line.

# Selenium WebDriver Python coding
from selenium import webdriver
import Utilities as U
exec_path = r"E:\Training\SeleniumPython\Downloads\geckodriver-v0.26.0-win32\geckodriver.exe"
URL = "https://www.youtube.com/playlist?list=PLc3SzDYhhiGUPPWt_rIVszepL1nMTbDaW"

driver = webdriver.Firefox(executable_path=exec_path)
driver.get(URL)
U.screenshot(driver)
# Close the browser with the Selenium WebDriver quit method.
driver.quit()

Want to learn how the above user defined functions work in action? Or how to implement the screenshot function in an existing Selenium Python test automation script? Then, please view my Selenium Python Screenshot Tutorial. Thank you.

July 06, 2020

Selenium Python Tutorial 9 | python selenium copy paste | Keyboard Actions in selenium python | Keys and PyAutoGUI

Moving on to the next tutorial in the Selenium Python Tutorials for Beginners. This Selenium Python beginner tutorial explains keyboard actions in Selenium Python using the Keys and PyAutoGUI libraries. The keyboard actions are send keys, edit text, copy and paste text and set focus using the keyboard. First, view the Selenium Python Copy Paste Tutorial. Then read on. 
 
Here is my first Selenium Python example with explicit wait. I have put explanations in the comments within the code (lines starting with #).

# Selenium WebDriver Python coding
# Type something in the Distance textbox and copy it to the speed textbox.
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as W
from selenium.webdriver.support import expected_conditions as E
from selenium.webdriver import ActionChains as A
from selenium.webdriver.common.keys import Keys as K

exec_path = r"E:\Training\SeleniumPython\Downloads\geckodriver-v0.26.0-win32\geckodriver.exe"
URL = "https://inderpsingh.blogspot.com/2014/08/demowebapp_24.html"
distance_id_locator = "distance"
speed_id_locator = "speed"
wait_time_out = 15
driver = webdriver.Firefox(executable_path=exec_path)
# Define variable for WebDriverWait Python.
wait_variable = W(driver, wait_time_out)
# Navigate to the URL given above.
driver.get(URL)
# Define the ActionChains object named a (to do keyboard actions).
a = A(driver)
distance_element = wait_variable.until(E.presence_of_element_located((By.ID, distance_id_locator)))
speed_element = wait_variable.until(E.presence_of_element_located((By.ID, speed_id_locator)))
# Type some text in the Distance text box using send keys.
distance_element.send_keys("123456")
# Python Selenium select all text using Ctrl+A
a.key_down(K.CONTROL).send_keys("a").perform()
# Python Selenium copy text to clipboard using Ctrl+C
a.key_down(K.CONTROL).send_keys("c").perform()
# Set focus to the Speed text box.
a.click_and_hold(speed_element).perform()
# Python Selenium paste text using Ctrl+V i.e. Python Selenium copy paste
a.key_down(K.CONTROL).send_keys("v").perform()

Here is my second Selenium Python example using PyAutoGUI, which I find having a number of features for keyboard actions and easy to use. You install the PyAutoGUI package with the pip command in the Command Prompt. Then install the PyAutoGUI package in the project under File menu>Settings>Project Interpreter. I explained such tasks here.

# Selenium WebDriver Python coding
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as W
from selenium.webdriver.support import expected_conditions as E
import pyautogui as P

exec_path = r"E:\Training\SeleniumPython\Downloads\geckodriver-v0.26.0-win32\geckodriver.exe"
URL = "https://inderpsingh.blogspot.com/2014/08/demowebapp_24.html"
distance_id_locator = "distance"
wait_time_out = 15
driver = webdriver.Firefox(executable_path=exec_path)
wait_variable = W(driver, wait_time_out)
driver.get(URL)
distance_element = wait_variable.until(E.presence_of_element_located((By.ID, distance_id_locator)))
# Call send keys method to send an empty string to set focus to the Distance text box.
distance_element.send_keys("")
# Call PyAutoGUI write method to type text in the Distance text box.
P.write("123456.78")
P.sleep(1)
# Call PyAutoGUI press method to press backspace key 3 times i.e. remove ".78".
P.press("backspace", 3)
# Call PyAutoGUI hotkey method to press keyboard shortcut Ctrl+A i.e. Python Selenium select all.
P.hotkey("ctrl", "a")
# Call PyAutoGUI hotkey method to press keyboard shortcut Ctrl+C i.e. Python Selenium copy text from web page.
P.hotkey("ctrl", "c")
P.sleep(1)
# Call PyAutoGUI press method to set focus to Speed text box.
P.press("tab")
# Call PyAutoGUI hotkey method to press keyboard shortcut Ctrl+V i.e. Python Selenium paste text from clipboard.
P.hotkey("ctrl", "v")

Want to learn more? Want to see the above Python scripts in action? Then, please view my Selenium Python Keyboard Actions Tutorial. Thank you.

June 28, 2020

Selenium Python Tutorial 8 | Python Selenium Mouse Click | Mouse Action Chains | PyAutoGUI Mouse

This is the next tutorial in the Selenium Python Tutorials for Beginners. This Selenium Python beginner tutorial explains Python Selenium mouse actions. First view the Selenium Python Mouse Click Tutorial below. Then read on.
 Here is my first Selenium Python example. I have put explanations in the comments within the code (lines starting with #).
# Selenium WebDriver Python coding
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as W
from selenium.webdriver.support import expected_conditions as E
from selenium.webdriver import ActionChains as A

exec_path = r"E:\Training\SeleniumPython\Downloads\geckodriver-v0.26.0-win32\geckodriver.exe"
URL1 = "https://inderpsingh.blogspot.com/2014/08/demowebapp_24.html"
URL2 = "https://crossbrowsertesting.github.io/drag-and-drop"
heading_css_locator = ".post-body > div:nth-child(1) > div:nth-child(1) > form:nth-child(1) > h3:nth-child(1)"
distance_id_locator = "distance"
draggable_id_locator = "draggable"
droppable_id_locator = "droppable"
wait_time_out =15

# Define the Selenium WebDriver variable.
driver = webdriver.Firefox(executable_path=exec_path)
# Define the variable for Explicit Wait.
wait_variable = W(driver, wait_time_out)
# Navigate to URL1.
driver.get(URL1)
# Find the heading web element, on which to perform the mouse double click.
heading_element = wait_variable.until(E.presence_of_element_located((By.CSS_SELECTOR, heading_css_locator)))
distance_element = wait_variable.until(E.presence_of_element_located((By.ID, distance_id_locator)))
# Define the variable of type ActionChains for Mouse Action Chains.
a = A(driver)
# Selenium Python Mouse Double Click on heading web element
a.double_click(heading_element)
# Call one of the multiple Selenium Python Mouse Move methods.
# Note: Selenium Python Mouse move methods implement Selenium Python Mouse Hover too.
a.move_to_element_with_offset(distance_element, 0, 0)
# Selenium Python Mouse Click
a.click_and_hold(distance_element)
a.release()
# Type 1000 at the mouse pointer location i.e. the beginning of the distance web element.
a.send_keys("1000")
# Call ActionChains perform method to run all the methods queued thus far.
a.perform()

# Navigate to URL2.
driver.get(URL2)
draggable_element = wait_variable.until(E.presence_of_element_located((By.ID, draggable_id_locator)))
droppable_element = wait_variable.until(E.presence_of_element_located((By.ID, droppable_id_locator)))
# Define another variable of type ActionChains. 
b = A(driver)
# Python Selenium Mouse Drag and Drop
b.drag_and_drop(draggable_element, droppable_element)
# Right click the Mouse on the draggable web element.
b.context_click(draggable_element)
b.perform()

A reliable way to operate the mouse with Selenium WebDriver is to use the PyAutoGUI library. You install the PyAutoGUI package with the pip command. Then install the PyAutoGUI package in the project. I explained such tasks here. Here is my second Selenium Python example for Selenium Python Mouse Actions using PyAutoGUI.

# Selenium WebDriver Python coding
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as W
from selenium.webdriver.support import expected_conditions as E
import pyautogui as P
import time

exec_path = r"E:\Training\SeleniumPython\Downloads\geckodriver-v0.26.0-win32\geckodriver.exe"
URL = "https://inderpsingh.blogspot.com/2014/08/demowebapp_24.html"
distance_id_locator = "distance"
speed_id_locator = "speed"
wait_time_out = 15
driver = webdriver.Firefox(executable_path=exec_path)
wait_variable = W(driver, wait_time_out)
driver.get(URL)
driver.execute_script("window.scrollBy(0,120)","")
distance_element = wait_variable.until(E.presence_of_element_located((By.ID, distance_id_locator)))
distance_element.send_keys("1000")
speed_element = wait_variable.until(E.presence_of_element_located((By.ID, speed_id_locator)))
speed_element.send_keys("50")
# When this script is running, move the mouse pointer to the Calculate Travel Days button.
time.sleep(5)
x, y = P.position()
# Print the x and y coordinates of the Calculate Travel Days button.
print ("X is ", str(x), "Y is ", str(y))
# Give the x and y coordinates printed by the print statement above e.g. 222, 573. The 3rd argument (optional) is the time the mouse pointer should take to move to the x and y coordinates.
# Note: After locating the x, y coordinates by running this Python script once, you may comment out the above lines from time.sleep(5) to print ("X is ", str(x), "Y is ", str(y))
# PyAutoGUI mouse operations
P.moveTo(222, 573, 3)
# Python Selenium Mouse Click
P.leftClick()

Want to learn more details? Want to see the above Selenium Python examples working? Then, please view my Selenium Python Mouse Move and Mouse Click Tutorial. Thank you.

June 21, 2020

Selenium Python Tutorial 7 | Python selenium Loop through Links | Selenium Python Link Click

Moving on to the next tutorial in the Selenium Python Tutorials for Beginners. This Selenium Python beginner tutorial explains selenium python link click, selenium link text and how to loop through links with explicit wait. First, view the Selenium Python Link Text Link Click Tutorial below. Then read on. 
 
Here is my full Selenium Python example. I have put explanations in the comments within the code (lines or phrases starting with #).
# Selenium WebDriver Python coding
# Import webdriver library to use the Selenium WebDriver commands.
from selenium import webdriver
# Import the By library to find the links on the web page.
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as W
from selenium.webdriver.support import expected_conditions as E

exec_path = r"E:\Training\SeleniumPython\Downloads\geckodriver-v0.26.0-win32\geckodriver.exe"
URL = "https://inderpsingh.blogspot.com/"
wait_time_out = 15

driver = webdriver.Firefox(executable_path=exec_path)
# Navigate to the URL.
driver.get(URL)
wait_variable = W(driver, wait_time_out)
# We need to find the link before Python Selenium click link .
# Define the Python list called links.
links = wait_variable.until(E.visibility_of_any_elements_located((By.TAG_NAME, "a")))
print ("The total number of links is", len(links))
# Use for each loop to python selenium loop through links. It takes time to loop through links.
for link in links:
    print (link.text) # Selenium link text
# Selenium link click on the "Selenium Python Tutorials" link using WebDriverWait Python
wait_variable.until(E.element_to_be_clickable((By.LINK_TEXT, "Selenium Python Tutorials"))).click()
# Go back to the home page.
driver.back()
# Click the same link but with the partial link text to Selenium link click Python.
wait_variable.until(E.element_to_be_clickable((By.PARTIAL_LINK_TEXT, "Selenium Python"))).click()

Want to learn more? Please view my Selenium Python Link Click and Link Text Tutorial. Thank you.

June 14, 2020

Selenium Python Tutorial 6 | iFrame Frame and Alert

This is the next tutorial in the Selenium Python Tutorials for Beginners. This Selenium Python beginner tutorial explains how to handle selenium python frames and selenium python alert handling. A frame or iFrame is a smaller web page within the main web page. Selenium WebDriver cannot directly find a web element that is inside a frame. It raises the unable to find element exception. Therefore, you need to switch to the frame and then find the web element. An alert is a message box that pops up on the web page. Selenium WebDriver can dismiss or accept the alert. First, view the Selenium Python iFrame Alert Tutorial below. Then read on.

Here is my full Selenium Python example. I have put explanations in the comments within the code (lines or phrases starting with #).

# Selenium WebDriver Python coding
from selenium import webdriver
from selenium.webdriver.common.by import By
# Import two libraries needed for WebDriverWait Python
from selenium.webdriver.support.ui import WebDriverWait as W
from selenium.webdriver.support import expected_conditions as E
import time

exec_path = r"E:\Training\SeleniumPython\Downloads\geckodriver-v0.26.0-win32\geckodriver.exe"
URL = "https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_alert"
# Selenium Python iframe locator on the web page
frame_id_locator = "iframeResult"
button_css_locator = "body > button:nth-child(2)"
wait_time_out = 5

driver = webdriver.Firefox(executable_path=exec_path)
driver.get(URL)

# Selenium WebDriver code to find all the frames on the web page:
frames = driver.find_elements_by_tag_name("iFrame")
print("There are",len(frames),"frames on this web page.")
for f in frames:
    print("Frame Id:", f.get_attribute('id'), ",Frame Name:", f.get_attribute('name'), ",Frame Source:", f.get_attribute('src'))

wait_variable = W(driver, wait_time_out)
# Selenium Python iframe switch after waiting for the frame to be available
wait_variable.until(E.frame_to_be_available_and_switch_to_it(frame_id_locator))
wait_variable.until(E.presence_of_element_located((By.CSS_SELECTOR, button_css_locator))).click()
# Wait for the alert to appear.
wait_variable.until(E.alert_is_present())
time.sleep(2)
# Accept the Python Selenium alert.
driver.switch_to.alert.accept()
time.sleep(2)
# From selenium python iframe switch back to the main web page.
driver.switch_to.default_content()

Want to learn more and see Selenium WebDriver in action? Then, please view my Selenium Python Frames Alerts Tutorial. Thank you.

June 07, 2020

Selenium Python Tutorial 5 | Open Window or Tab | Python Selenium Switch To Window

This is the fifth tutorial in the Selenium Python Tutorials for Beginners. This Selenium Python beginner tutorial explains how to open another window or tab in the browser with Selenium WebDriver. First, view the Selenium Python Open Window or Tab Tutorial below. Then read on.

Here is my Selenium Python example. I have put explanations in the comments within the code (lines or phrases starting with #).

# Selenium WebDriver Python coding
from selenium import webdriver
# Give the location of the browser driver (the executable path). In Python, r means a raw string.
exec_path = r"E:\Training\SeleniumPython\Downloads\geckodriver-v0.26.0-win32\geckodriver.exe"
URL = r"https://www.wikipedia.org/"
# English language URL: https://en.wikipedia.org/
# Japanese language URL: https://ja.wikipedia.org/
# French language URL: https://fr.wikipedia.org/

# Define a Python list of languages.
languages = ["en", "ja", "fr"]
driver = webdriver.Firefox(executable_path=exec_path)
driver.get(URL)
# Print the Selenium WebDriver window handle of the original browser window.
print ("Window handle of the current window is", driver.current_window_handle)

for i in range(len(languages)):
    # Call Selenium WebDriver execute script method with Javascript to open another tab.
    driver.execute_script("window.open()")
    # Call Selenium WebDriver switch to method.
    # Selenium WebDriver window handles index 0 is the original tab.
    # In the for loop, use indexes starting from 1.
    driver.switch_to.window(driver.window_handles[i+1])
    language_URL = r"https://" + languages[i] + ".wikipedia.org/"
    driver.get(language_URL)
    print (language_URL, driver.window_handles[i+1], driver.title, driver.current_url)

Want to learn more? Want to see the above code working? Then, please view my Selenium Python Open Window or Tab Tutorial. Thank you.

May 31, 2020

Selenium Python Tutorial 4 | selenium python drop down list | Python WebDriver

This is the fourth tutorial in the Selenium Python Tutorials for Beginners. This Selenium Python beginner tutorial explains how to work with a DropDown using Selenium WebDriver. First, view the Selenium Python Drop Down List tutorial. Then read on.
 A dropdown is a web element that you can click to open a number of values. You may select any value from the options. Here is the test case to test the Journey Planner application.

Test stepExpected result
Navigate to the Journey Planner application.
Enter a distance, speed and time to travel.
Click the Calculate Results button.The result in days should appear.
Repeat the previous two test steps for each option in the DropDown box.

Here is my Selenium Python example that tests each option in the Selenium Python drop down list. I have put explanations in the comments within the code (lines or phrases starting with #).

# Selenium WebDriver Python coding
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as W
from selenium.webdriver.support import expected_conditions as E
# The Select library operates the drop down list.
from selenium.webdriver.support.ui import Select
import time

exec_path = r"E:\Training\SeleniumPython\Downloads\geckodriver-v0.26.0-win32\geckodriver.exe"
URL = "https://inderpsingh.blogspot.com/2014/08/demowebapp_24.html"
distance_id_locator = "distance"
distance = 0 # Assign some initial value to distance.
speed_id_locator = "speed"
speed = 45 # Assign some initial value to speed.
time_id_locator = "hours"
calculate_css_locator = ".post-body > div:nth-child(1) > div:nth-child(1) > form:nth-child(1) > button:nth-child(20)"
result_id_locator = "result"
wait_time_out = 5

# Define the Python WebDriver
driver = webdriver.Firefox(executable_path=exec_path)
driver.get(URL)
wait_variable = W(driver, wait_time_out)
# JavaScript to scroll window down by 240 pixels
driver.execute_script("window.scrollBy(0,240)", "")
# Find web elements using WebDriverWait Python.
distance_element = wait_variable.until(E.presence_of_element_located((By.ID, distance_id_locator)))
speed_element = wait_variable.until(E.presence_of_element_located((By.ID, speed_id_locator)))
# Time_element is a drop down list. Call the Select method on Explicit Wait.
time_element = Select(wait_variable.until(E.presence_of_element_located((By.ID, time_id_locator))))
calculate_element = wait_variable.until(E.presence_of_element_located((By.CSS_SELECTOR, calculate_css_locator)))
result_element = wait_variable.until(E.presence_of_element_located((By.ID, result_id_locator)))
# time_element.options is the list of all the options in the dropdown list.
for option in time_element.options:
    distance_element.clear()
    distance += 100 # Generate distance test data by adding 100 to it's previous value.
    distance_element.send_keys(distance)
    speed_element.clear()
    speed += 1 # Generate speed test data by adding 1 to it's previous value.
    speed_element.send_keys(speed)
    time_element.select_by_visible_text(option.text) # Select the dropdown option.
    calculate_element.click()
    time.sleep(1)
    # Calculate the expected result using my own calculation.
    expected_result = round(float(distance)/float(speed)/float(option.get_attribute("value")),4)
    if expected_result == int(expected_result): expected_result = int(expected_result)
    # Validate by comparing expected result with the actual result from the application.
    if str(expected_result) in result_element.text:
        print ("Passed", str(expected_result), result_element.text)
    else:
        print ("Failed", str(expected_result), result_element.text)

Want to learn more e.g. how to find the web element locators and see the above code working? Please view my Selenium Python Drop Down List tutorial. Thank you.

May 24, 2020

Selenium Python Tutorial 3 | selenium python Checkbox | Example to click Check Boxes Combinations

This is the third tutorial in the Selenium Python Tutorials for Beginners. This Selenium Python beginner tutorial explains how to work with selenium python checkbox. A checkbox is a web element that belongs in a group of checkboxes. You can select none, any or all check boxes in that group.. First, view the Selenium Python Checkbox tutorial. Then read below.
Here is my Selenium Python example to click checkboxes combination until the answer is correct, for each question in my HTML Quiz.

# Selenium WebDriver Python coding
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as W
from selenium.webdriver.support import expected_conditions as E
# Import the checkbox user defined function file below.
import CheckboxFunctions as C

exec_path = r"E:\Training\SeleniumPython\Downloads\geckodriver-v0.26.0-win32\geckodriver.exe"
URL = "https://inderpsingh.blogspot.com/2013/01/HTMLCSSQuiz1.html"
wait_time_out = 15
check_name_locator = "option"
driver = webdriver.Firefox(executable_path=exec_path)
wait = W(driver, wait_time_out)
# Navigate to the Quiz web page.
driver.get(URL)

i = 0
while i < 10:
    # The counter variable, i, represents the question number in the quiz.
    i += 1
    # Selenium Python scrolling the web page down by 120 pixels
    driver.execute_script("window.scrollBy(0,120)","")
    check_element_1 = wait.until(E.presence_of_element_located((By.NAME, check_name_locator + str(i) + "1")))
    check_element_2 = wait.until(E.presence_of_element_located((By.NAME, check_name_locator + str(i) + "2")))
    check_element_3 = wait.until(E.presence_of_element_located((By.NAME, check_name_locator + str(i) + "3")))
    # Check each checkbox by clicking it. 
    check_element_1.click()
    check_element_2.click()
    check_element_3.click() # Check checkbox 1, 2 and 3.
    # C is the alias for CheckboxFunctions Python script.
    # If answered returns True, skip the remainder of the while loop with continue statement.
    if C.answered(driver, i): continue
    check_element_1.click() # Check checkbox 2 and 3 only.
    if C.answered(driver, i): continue
    check_element_1.click()
    check_element_2.click() # Check checkbox 1 and 3 only.
    if C.answered(driver, i): continue
    check_element_2.click()
    check_element_3.click() # Check checkbox 1 and 2 only.
    if C.answered(driver, i): continue
    check_element_2.click() # Check checkbox 1 only.
    if C.answered(driver, i): continue
    check_element_1.click()
    check_element_2.click() # Check checkbox 2 only.
    if C.answered(driver, i): continue
    check_element_2.click()
    check_element_3.click() # Check checkbox 3 only.
    if C.answered(driver, i): continue
#driver.quit()

The above Test Automation code calls the answered user defined function that I wrote in CheckboxFunctions.py file below.

# Selenium WebDriver Python coding
from selenium.webdriver.common.by import By
# The following two import statements are for webdriverwait Python (explicit wait).
from selenium.webdriver.support.ui import WebDriverWait as W
from selenium.webdriver.support import expected_conditions as E
import time
wait_time_out = 15

def answered(d, question_number):
    # function documentation on the next line
    """Locate the answer element. Return True or False based on the value attribute."""
    wait_variable = W(d, wait_time_out)
    answer_element = wait_variable.until(E.presence_of_element_located((By.NAME, "answer" + str(question_number))))
    time.sleep(0.25)
    if "Correct." in answer_element.get_attribute("value"):
        return True
    else:
        return False

Want to understand the Selenium Python code better and see it working? Please view my Selenium Python Checkbox tutorial. Thank you.

May 14, 2020

Selenium Python Tutorial 2 | Python Automation Testing | Selenium Python Radio Button

This is the second tutorial in the Selenium Python Tutorials for Beginners. This Selenium Python beginner tutorial explains how to work with radiobuttons. First, view the Selenium Python Radio Button tutorial. Then read below.
 

A radiobutton is a web element that belongs in a group of radiobuttons. Exactly one radiobutton can be selected in that group, meaning the radio button selection is mutually exclusive. Here is my first Selenium Python example to answer Question 1 of my Selenium WebDriver Quiz.

# Selenium WebDriver Python coding
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as W
from selenium.webdriver.support import expected_conditions as E

exec_path = r"E:\Training\SeleniumPython\Downloads\geckodriver-v0.26.0-win32\geckodriver.exe"
URL = "https://inderpsingh.blogspot.com/2013/04/SeleniumWebDriverQuiz4.html"
wait_time_out = 5
# Give the locator for Selenium Python Radio Button
answer1_radio_id_locator = "13"
answer1_name_locator = "answer1"

driver = webdriver.Firefox(executable_path=exec_path)
wait = W(driver, wait_time_out)
driver.get(URL)
# Use explicit wait (webdriverwait python) to find the radiobutton.
radio_element = wait.until(E.presence_of_element_located((By.ID, answer1_radio_id_locator)))
radio_element.click()
answer1_element = wait.until(E.presence_of_element_located((By.NAME, answer1_name_locator)))

# Validate the test result.
if "Correct." in answer1_element.get_attribute("value"):
    print ("Test passed.")
else:
    print ("Test failed.")

Here is my second Selenium Python example, that answers the quiz automatically using Python browser automation.

# Selenium WebDriver Python coding
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as W
from selenium.webdriver.support import expected_conditions as E
import time

exec_path = r"E:\Training\SeleniumPython\Downloads\geckodriver-v0.26.0-win32\geckodriver.exe"
URL = "https://inderpsingh.blogspot.com/2013/04/SeleniumWebDriverQuiz4.html"
wait_time_out = 5
answer_name_locator = "answer"
score_id_locator = "score"
driver = webdriver.Firefox(executable_path=exec_path)
wait = W(driver, wait_time_out)
driver.get(URL)
# Run a loop for the question number 1 through 6.
for q in range(1, 7):
    # Run a loop for the answer number 1 through 4.
    for a in range(1, 5):
        # Craft the locator for Selenium Python Radio Button.
        radio_element = wait.until(E.presence_of_element_located((By.ID, str(q) + str(a))))
        radio_element.click()
        time.sleep(1)
        answer_element = wait.until(E.visibility_of_element_located((By.NAME, answer_name_locator + str(q))))
        if "Correct." in answer_element.get_attribute("value"): break

#validation
score_element = wait.until(E.visibility_of_element_located((By.ID, score_id_locator)))
if "6/6" in score_element.text:
    print ("Test is passed.")
else:
    print ("Test is failed.")

That is all in this Python Automation Testing tutorial. Want to see the above Selenium Python code working in the PyCharm IDE? Please see my Selenium Python Radio Button tutorial. Thank you.