December 20, 2020

SelectorsHub Introduction | SelectorsHub tutorial for CSS selectors and XPath locators

This post introduces SelectorsHub, which is a free tool to find correct CSS selectors and XPath locators automatically. CSS selectors and XPath locators can be tough to write for beginners in test automation, like those learning Selenium WebDriver automated testing, or take time to write for experienced web developers and test automators. SelectorsHub automatically suggests complete selectors like CSS selectors, XPath and other web element locators. View SelectorsHub demonstration to find CSS selector like CSS Id and Css Class Selector or read on.

View SelectorsHub demonstration on how to find XPath in Chrome Browser and how to find XPath in Firefox. SelectorsHub is also available for Edge and Opera browsers.

SelectorsHub may help you improve XPath and CSS selectors writing skills. It offers choices of selectors and locators with the number of occurrences of each. SelectorsHub works with shadow DOM and svg element. It also gives the error message if case of any mistake in your written selector. SelectorsHub's user interface may be customized, if you want. View the demonstration of SelectorsHub features and benefits.

For details, check out What is SelectorsHub. You may also contact Sanjay Kumar, the inventor of SelectorsHub. Thank you.

November 01, 2020

Perl Split | Perl Function | String Functions in Perl | Perl Scripting | Perl Programming

This is a Perl tutorial on Perl Split and other string functions in Perl from the Perl Tutorials. Perl language has many functions for string processing, that are useful for processing HTML and XML. This tutorial explains some important string functions in Perl. First, view the Perl Split and String Functions tutorial. Then read below.

Let us learn Perl scripting with examples. Here is the first Perl script example with Perl function lc (to convert a string to lower case) and Perl function uc (to convert a string to upper case):

# Perl code example
# First, implement Perl basics.
use strict; # Perl use strict finds any error in the Perl code if found, stops running the code.
use warnings; # Perl use warnings gives a warning if there is any problem with the Perl code.
use feature qw(say); # say is better than Perl print statement because it appends a newline automatically.
# Perl my to declare a variable in Perl
my $blog = "Software Testing Space";
# string functions in Perl
# Perl print variable in lowercase
say "The blog name in lower case is ", lc($blog);
# Perl uppercase or Perl uc string function
say "The blog name in upper case is ", uc($blog);

Here is another Perl scripting example with length Perl function, Perl string operations and index Perl function (to find a substring within a Perl string):

# Perl code example
use strict; # Perl use strict
use warnings; # Perl use warnings
# use strict and use warnings help us write the correct Perl code in Perl programming.
use feature qw(say); # better form of Perl print
# Perl basics are addressed above. Now, write the actual Perl code.
my $name = "Inder P Singh"; # string assignment
say "The length of name, including spaces, is ", length($name);
# Perl expression of string multiplication using x string operator
# . is string the string operator for concatenation
say "The repeated name is ". $name x 3;
my $text = "abcdef";
# Perl find by index; The indexes are 0-based, meaning they start from 0.
say "The string de occurs in text at ", index($text, "de");
 #index string function returns -1 if the substring is missing in the string.
say "The string x occurs in text at ", index($text, "x");

Here is another Perl example with join Perl function, reverse Perl function and Perl split:

# Perl code example
use strict;
use warnings;
use feature qw(say);
# Perl my
my $blog = "Software Testing Space";
# An array variable in Perl can store a list of values.
my @letters = ("a".."j");# An array is declared within parentheses as a range.
# Perl print array; a Perl array is 0-based.
say "The first five letters are ", @letters[0..4]; # Print the first 5 elements of the array.
# join string function returns the joined string with a separator.
say "The joined letters are ", join(":",@letters);
# reverse string function returns the string with the characters in reverse order.
say "The reverse of letters is ",  reverse(@letters);
# Based on a pattern, the split function in Perl returns a list of strings.
# The pattern in Perl split is given within a pair of forward slashes.
# The pattern is a single space character below.
say "The words in the blog are ", split(/ /,$blog); # Perl split
# Split command in Perl with another Perl example, using join with Perl split
say "The comma separated words in the blog are ", join(",",split(/ /,$blog)); # Perl split command

Want to learn Perl more and see the above Perl examples run? Then please view my Perl Split | String Functions in Perl tutorial. Thank you.

October 21, 2020

Perl For Loop - Perl foreach - perl for | Perl Scripting | Perl Programming

This is the Perl tutorial on Perl for loop and Perl foreach from the Perl Tutorials. Perl for loop can be used to run a code block multiple times. Perl foreach loop is a more convenient form of the Perl for loop. First, view the Perl For Foreach tutorial. Then read below.
 
Perl code can be written in any text editor. The Perl pl script should have the .pl file extension. We can run Perl script within the Command Prompt app. In the Command Prompt window, change directory using cd command to the folder that has our Perl script. Then run the command, perl scriptname.pl 
 
Using Perl for statement, we can run a code block multiple times depending on an initial value, a condition and an action. Here is the first Perl script example with the Perl for loop. This Perl scripting example should print 1, 2 and 3 on different lines.
 
use strict; # Perl use strict finds an error in the code and stops the Perl code if there is an error.
use warnings; # Perl use warnings gives a warning in case of an issue with Perl code.
my $i; # In Perl language, Perl my is used to declare a variable in Perl.
# In this Perl for loop, the initial value of variable i will be 1.
# This Perl for loop will check the condition that i is less than or equal to 5. If true, the Perl for loop will be run once.
# This Perl for loop will increase the value of i by 1 i.e. if i was 1, i will become 2 and so on.
for ($i=1;$i<=5;$i++) {
    # In Perl scripting language, Perl sleep is used to make the script pause for given seconds.
    # if no time is specified, Perl sleep makes the script wait indefinitely.
    sleep 1;
    print "The counter is $i\n"; # Perl print the variable i
    if ($i eq 3){
        # Perl break - last to Perl break out of loop
        last;
    }
}
 
Using Perl foreach statement, we can run a code block multiple times for each value in a list of values. Here is the second Perl script example with the Perl foreach loop. This Perl scripting example should print the first value as 1, the final value as 10. Then it should print all values in the list as 1, 2, 3, 5 and 10.
 
use strict; # In Perl programming, Perl use strict finds an error in the code.
use warnings; # Perl use warnings gives a warning if any issue with Perl code is observed.
# Array variable in Perl can store a list of values.
# The Perl array name is prefixed with @.
# An array is declared within parentheses.
my @scores = (1, 2, 3, 5, 10);
# An array element is accessed with square brackets. A Perl array is 0-based.
print "The first score is $scores[0] \n";
# One of the Perl special variables, $#array gives the last index of the Perl array.
print "The final score is $scores[$#scores]\n";
foreach (@scores){
    # Perl foreach will run for each element of @scores array in Perl
    # $_ is the default special variable automatically set by the Perl foreach loop.
    print "The score is $_\n"; # Perl print array
}

Want to learn Perl more or see the above Perl scripts running? Then please view my Perl For Foreach Tutorial. Thank you.

October 11, 2020

Perl | Perl Scripting - Perl If - Perl If Not Statement | Perl Programming

This is the Perl tutorial on Perl if and Perl if not statements from the Perl Tutorials. Perl language is a general-purpose and open source programming language. Perl language is useful for regular expression parsing and text processing (like HTML, XML etc.). Perl language is efficient, simple to learn and use and has many libraries. There is use of Perl scripting language in tasks such as system administration, web based development etc. We can use Perl scripting language to write from simple scripts to complex applications. Perl coding language has many features. View the Perl If tutorial. Then read below.
 
Installing perl on Windows is straight-forward. I have explained Strawberry Perl with Setup Wizard screenshots in the initial part of the above Perl tutorial. The Strawberry Perl Setup Wizard should automatically update the Path system variable in Windows 10.
 
You can write Perl code using any text editor. The Perl pl script has to be saved with .pl file extension. Running Perl script can be done by running the Command Prompt app in Windows 10. In the Command Prompt window, change directory using cd command to the folder that has your pl script. Then run the command, perl yourscriptfilename.pl
 
Since this tutorial is regarding Perl scripting for beginners, let us start with Perl basics. Here is the first Perl script example. Other Perl programming examples are below.

# This is a Perl script, meaning it has at least one statement in the Perl scripting language.
# Each Perl scripting statement ends with a semi-colon.
# Comments in Perl start with a # sign.
use strict; # Perl use strict finds an error in the code and stops running the Perl code.
use warnings; # Perl use warnings gives a warning in case of a problem.
# A string is some text. A string has to have a pair of double quotes around it.
# Or a string literal has to have a pair of single quotes around it.
print "Welcome to Perl Training"; # Perl print statement

If you have run the above Perl example, let us continue to learn Perl. Here is another Perl example to show more Perl basics.

use strict; # Perl use strict finds any error in the Perl code.
use warnings; # Perl use warnings gives a warning, if needed.
my $name = "John";  # Perl my keyword is used to declare a variable, $name
my $number = 100; # Perl my declares the Perl variable, $number
print "My name is ", $name, "\n"; # Perl print variable value, \n takes the cursor to the next line
print "The half of number is ", $number/2; # Perl print Perl expression

Perl if statement is used to conditionally run a code block. The condition in Perl if is put within parentheses. A Perl code block is one or more Perl statements that are enclosed within curly braces. The Perl condition is followed by the Perl if code block. Optionally, another Perl condition can be given after elsif in the Perl if statement. The Perl elsif has it's own code block. The remaining condition is handled by the Perl else. The Perl else has it's code block after it. Here is a Perl script example for Perl compare string. Run the following Perl example with $string2 variable having mulitple values like "abc", "def" and "ABC".
 
use strict; # Perl use strict
use warnings; # Perl use warnings
my $string1 = "abc"; # Declare the Perl variable, $string1 to store a Perl string.
my $string2 = "abc"; # Declare the Perl variable, $string2, to store the second string.
if ($string1 eq $string2){ # The condition is $string equals $string2.
    print "The two strings are the same.";
}
elsif ($string1 lt $string2){ # Perl elsif condition is $string1 less than $string2.
    # The variable name can even be written inside the string to print the variable's value.
    print "$string1 is smaller than $string2";
}
else {# A code block starts with the left curly brace, {
    print "$string1 is greater than $string2";
} # A code block ends with the right curly brace, }

Perl if not statement is also used to conditionally run a code block. There is a not operator, !, before the condition. The not operator reverses the condition, meaning the condition if true becomes false and vice versa. Here is another Perl code example for Perl compare string in Perl programming. Perl compare string is case sensitive. Run the following Perl example with other values also for the second Perl string, like "a" and "Abc".
 
use strict;
use warnings;
if (!("abc" eq "abc")){
    print "The two strings are different.";
}
else{
    print "The two strings are the same.";
}

Want to learn Perl more? Want to see the above Perl script example running? Then please view my Perl If - Perl If Not tutorial. Thank you.

September 27, 2020

Technology Partners

Technology Partners

SelectorsHub : Innovation Inspired Automation!

MaxTAF Cloud :  SaaS Platform for Inevitable Automation Success





 

August 24, 2020

Domain Knowledge for Testers - Banking Domain Knowledge | ECommerce Domain Knowledge | Telecom Domain Knowledge | ERP Domain Knowledge

This blog post relates to domain specific knowledge videos in the Banking, ECommerce, Telecom, ERP and Automotive industry domains. Business domain knowledge is important to be productive as a software tester. What is domain knowledge meaning? Domain knowledge in software testing is knowledge of the concepts, vocabulary and terms used in a particular industry or domain.

Banking Domain Knowledge for Testers | Bank domain knowledge video : This Banking Domain Knowledge or Business Domain Knowledge in the Banking Domain video covers What is Bank, what is Spread, Banking Channels (e.g. ATM banking, internet banking, mobile banking, phone banking, relationship manager banking and DSA banking), Retail Banking products such as Savings bank account, Recurring deposit account, Fixed deposit account, Certificate of deposit, Term deposit, IRA, Credit card, Debit card, ATM card, Mortgage, Mutual fund, Personal loan, Cheque, NEFT and RTGS, and domain knowledge for software testers including Business Banking or Corporate Banking products such as Current account, Overdraft (Revolving Credit), Business loan, Term loan and Cash management) and Investment Banking (raising capital, mergers and acquisitions and trading securities).

ECommerce Domain Knowledge | E commerce domain knowledge for Testers video : The video is on domain specific knowledge in E-Commerce industry. There are both physical and digital ecommerce products and e commerce services. Ecommerce marketing uses email, online advertisements, social media and price comparison websites that use affiliate marketing. ECommerce domain knowledge includes knowledge about B2B (business to business), B2C (business to consumer) and C2C (consumer to consumer) e commerce. Also, ECommerce business knowledge includes knowledge of retail ECommerce, online auctions and Ecommerce market places.

Telecom Domain Knowledge for Testers | Telecom Domain Basics video : This video is on telecom domain knowledge or business domain knowledge in telecom. Telecom  is short for telecommunication. The video covers telecom domain basics like 1G, 2G, 3G, 4G and 5G telecom standards with GSM, CDMA, UMTS, LTE and NR. Also OSS meaning Operations Support Systems and BSS meaning Business Support Systems. This telecom domain training may be useful to build domain knowledge for testers.
OSS TeleCom | What is Oss in Telecom | oss full form in telecom video : This OSS telecom tutorial explains the OSS computer systems that are used in the telecom industry domain. An OSS is used by the telecom provider to manage customer orders and telecom network operations. OSS functions include network inventory (physical and logical), provisioning and activation, assurance of service quality to the customer - preventive service assurance and corrective service assurance, fault management process and customer care with metrics.
BSS TeleCom | What is Bss in Telecom | bss telecom full form - Domain Knowledge (oss bss telecom) video : This BSS telecom tutorial explains the BSS computer systems that are used in the telecom industry domain. Bss in telecommunication domain has important functions or processes used by the telecom provider or telco.  These are product management, new order management, revenue management and customer management. Note that OSS BSS telco communicate with each other.
 
ERP | Erp System | ERP software - Domain Knowledge for Testers video : This video is on ERP domain Knowledge. It covers what is ERP and the benefits of ERP,  Erp system integration and ERP software examples like Tally ERP 9 software,  SAP ERP system (SAP ERP modules and ECC SAP) and Dynamics Nav. This video may be useful to build domain knowledge for software testers.
 
 
Automotive Industry | Automotive Part - Automotive Domain Knowledge video : Automotive industry deals with wheeled automobiles like cars and goods vehicles. An automotive part is a component of an automobile. This video on automotive domain knowledge covers the automotive industry a.k.a. the auto sector, auto part categories and automotive terminology.

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.