Showing posts with label Open Source Tools. Show all posts
Showing posts with label Open Source Tools. Show all posts

May 10, 2020

Selenium Python Tutorial 1 | Selenium WebDriver python | Python Automation Testing | Python WebDriver

This is the first tutorial in the Selenium Python Tutorials for Beginners. This Selenium Python beginner tutorial gives an introduction to Python and Selenium WebDriver, pip install Selenium and multiple selenium python example. First, view the Selenium Python tutorial 1. Then read below.
You can do Python browser automation with Selenium WebDriver. Python programming language is also used for web development, game development, machine learning and other applications. The Selenium library Python is open source and free. Selenium tests web applications in multiple browsers.

In order to work with selenium using python, we need to install Python 3, which we can install from the Python official website. Next, how to Python install Selenium? We can use pip, which is the Python package installer. In the command prompt, the pip install Selenium command is below. This command gets the Selenium Python download or the Selenium package from the Selenium official website.

pip install -U selenium

For Python Selenium automation, we can create a new project in the PyCharm IDE. Click File> New Project. Then give the name of the project. In order to configure Selenium WebDriver in this project, select the project. Click File > Settings > Project > Project interpreter. It shows the packages that are available. Click + button, which is the Install button. It shows all the available packages. In the search text box, type selenium. Select selenium and click Install Package button. It gives the message, Package 'selenium' installed successfully. Click close button. Then it shows selenium in the packages list also. Click OK button. Next, right-click the Project > New > Python file. Give a name and click OK button. We need to download the Python WebDriver libraries for the browsers. We can go to the Selenium website  and click on the Downloads tab. In the Selenium Client & WebDriver Language Bindings section, find Python and click the Download link. Here are the drivers for the browsers like Firefox (GeckoDriver), Chrome (ChromeDriver) and Edge (EdgeDriver) which we can download. Now, we are ready for selenium using python. Here is my first Selenium Python example:

# Selenium WebDriver Python coding
# Import WebDriver library from the Selenium package
from selenium import webdriver
# Import By to find elements on the web page
from selenium.webdriver.common.by import By

# Give the location of the browser driver. r means a raw Python string.
exec_path = r"E:\Training\SeleniumPython\Downloads\geckodriver-v0.26.0-win32\geckodriver.exe"
URL = r"https://www.wikipedia.org/"
english_link_locator = "js-link-box-en"
search_locator = "searchInput"
search_text = "Software"

# Define the Selenium WebDriver variable with the executable path.
driver = webdriver.Firefox(executable_path=exec_path)
# Navigate to the URL.
driver.get(URL)
driver.maximize_window()
# Find the English link.
english_link_element = driver.find_element(By.ID, english_link_locator)
english_link_element.click()
# Find the Search text box.
input_box_element = driver.find_element(By.ID, search_locator)
input_box_element.send_keys(search_text)
input_box_element.submit()
# The quit method closes the browser windows.
# driver.quit()

Here is my second Selenium Python example with WebDriverWait Python using multiple language link locators :

# Selenium WebDriver Python coding
from selenium import webdriver
from selenium.webdriver.common.by import By
# Import statements for explicit wait
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 = r"https://www.wikipedia.org/"
# Define a list of locators for the language links.
language_locators = ["js-link-box-en", "js-link-box-ru", "js-link-box-de"]
search_locator = "searchInput"
search_text = "Software"
wait_time = 5

driver = webdriver.Firefox(executable_path=exec_path)
driver.get(URL)
# Define the wait variable for explicit wait.
wait = W(driver, wait_time)
driver.maximize_window()
for i in range(len(language_locators)):
    language_link = wait.until(E.presence_of_element_located((By.ID, language_locators[i])))
    language_link.click()
    input_box_element = wait.until(E.presence_of_element_located((By.ID, search_locator)))
    input_box_element.send_keys(search_text)
    input_box_element.submit()
    # Pause the script for a few seconds.
    time.sleep(4)
    driver.back()
    driver.back()
# driver.quit()

That is all in this Python Automation Testing tutorial. Want to learn more details like how to find the locators? Want to know about the synchronization issue in Test Automation and how to resolve it? Or want to see the above Selenium Python code working? Please view my Selenium Python tutorial 1. Thank you.

January 19, 2020

Python tutorial 19 | Classes and Instance Objects

This is the last tutorial in the Python Tutorials for Beginners. This Python beginner tutorial explains Python classes and Python objects. Please view the Python video tutorial 19 or read on... What is class in Python programming? A class is a template or a pattern to create objects. Python classes support object-oriented programming. A Python class has class attributes. Also, a Python class can be updated after it's definition. The objects created from a Python class are called instance objects. The Python class syntax is:

class ClassName:
  class body

In the above class format, the Python keyword class is followed by the name of the class, then a colon and then one or more Python statements. Now, let us see Python class examples.

# Python code
class Tree:
    """A class that represents a tree""" # doc string - optional
    species = 'Pine' # class attribute - data attribute
    def describe_me (self): # class attribute - class method
        return 'this is a tree'

# print the data attribute of the Tree class i.e. print 'Pine'
print (Tree.species)
# print the documentation string of the Tree class
print (Tree.__doc__)
# update the Python class (after class definition)
Tree.species = 'Aspen'
print (Tree.species)

# class instantiation i.e. create objects
tree1 = Tree()
# note that there is no need to provide the self argument when calling the class method, describe_me()
print (tree1.describe_me(), 'of species', tree1.species)
# find out if tree1 is an object of the class Tree or not
print (isinstance(tree1, Tree))

January 12, 2020

Python tutorial 18 | Dictionaries

Moving on to the next tutorial in the Python Tutorials for Beginners. This Python beginner tutorial explains the dictionary data structure. Please view the Python video tutorial 18 or read on... What is dictionary in Python programming? It is a group of key value pairs, that may be stored in any order. The Python dictionary keys can be strings or numbers (immutable data types only). Also, each dictionary key is unique. Python dictionaries are mutable, meaning that any dictionary item may be updated. In other programming languages, dictionaries may be called associative arrays. The dictionary syntax is:

{key0:value0, key1:value1,..., keyn:valuen}

In the above  dictionary format, the key value pairs are separated by commas. The first item is key0:value0, the second item is key1:value1 and so on. The entire group of key value pairs is enclosed within curly braces. Now, let us see Python dictionary examples, Python dictionary operations and Python dictionary functions.

# Python code
num_to_words = {1:'one', 2:'two', 10:'ten', 3:'three', 5:'five'}
# print the Python dictionary (the items may be in any order)
print (num_to_words)
# print the Python dictionary item's value for the given key i.e. print 'three'
print (num_to_words[3])
# modify the Python dictionary item's value for the given key
num_to_words[1] = 'unity'
# print the updated value i.e. print 'unity'
print  (num_to_words[1])

January 06, 2020

Python tutorial 17 | Tuples

Let us go to the next tutorial in the Python Tutorials for Beginners.  This Python beginner tutorial explains the tuple sequence data type. Please view Python video tutorial 17 or read on... What are tuples? In Python programming, a tuple is a sequence of items. The tuple items may be of the same data type or different data types like integers, floats, strings, lists or other tuples. The tuple items are commonly of different data types. Tuples are immutable, meaning that after a tuple is defined, no tuple item can be updated. Also, a tuple that is an item in another tuple is called a nested tuple. The tuple syntax is:
item0, item1, item2,..., itemn

The tuple syntax can also be the items within parentheses.
(item0, item1, item2,..., itemn)

In the above tuple format, the items are separated by commas. The item indexes start from 0.  Now, let us see Python tuple examples and tuple operations with Python examples.

January 01, 2020

Python tutorial 16 | Exception handling part 2 | Try except statement

Moving on with Python Tutorials for Beginners, let us go to the next one from Exception Handling part 1 tutorial. This Python beginner tutorial further explains how to handle any exception in Python. Please view the Python video tutorial 16 or read on... I have explained what are exceptions in my previous Python tutorial 15. In Python programming, the Python try statement syntax can also have an optional else clause:

try:
    try clause
except named_exception(s):
    except clause

else:
    else clause

In the above try statement format, we can put code in the else clause that will only be run when no exception is thrown in the try clause. In other words, the else clause should have code to be be run after the successful completion of the try clause. The else clause may be written after multiple excepts also. Now, let us see the else clause Python examples.

# Python code example
# This Python code, as is, should run the else clause.
try:
    i = 10 # if you comment this line, it should generate an exception and skip the else clause
    print (i*2)
except NameError:
    print ('Please define the variable first.')
else:
    print ('Printed the double of the value!')

The Python try statement syntax can also have an optional finally clause:
try:
    try clause
except named_exception(s):
    except clause

else:
    else clause
finally:
    finally clause

December 22, 2019

Python tutorial 15 | Exception handling part 1 | Try except statement

Let us go to an important tutorial in the Python Tutorials for Beginners. This Python beginner tutorial explains exceptions in Python and how to handle them. First, what are exceptions? Exceptions are the errors that are thrown during script execution. Exceptions are different from syntax errors, which are thrown before script execution. If we do not handle an exception, our script execution stops with an error message. Let us see some Python exception examples.

# Python code
print (i * 2)   # throws NameError exception because variable 'i' is not defined
int ('Hi')   # throws ValueError exception because 'Hi' is an invalid argument to the int function
print (1 / 0)   # throws ZeroDivisionError because division by zero is not allowed in Python programming

We can handle exceptions in Python using the Python try except statement. This means that we can protect our Python script from stopping abruptly. The Python try statement syntax is:
try:
    try clause
except named exception:
    except clause

In the above try statement format, the try clause is a code block with one or more statements in it. Same for the except clause. When Python runs the try clause, there are three possibilities 1), 2a) or 2b):
1) If there is no exception, the try clause is completed and the except clause is skipped.
2) If an exception is thrown in the try clause, the remaining statements in the try clause are skipped. Python matches the thrown exception with the named exception(s) after except:
2a) If the exception matches, the except clause  is run.
2b) If the exception does not match, the Python script execution stops with an error message.

Now, let us see the Python try except statement example.

# Python code example
try:
    i = 10 # comment this line to generate an exception
    print (i*2)
except NameError:
    print ('Please define the variable first.')

The Python try statement syntax can also have multiple excepts:
try:
    try clause
except named exception 1:
    except clause 1
except named exception 2:
    except clause 2
.
.
.
except named exception n:
    except clause n

In the above try statement format, there are multiple except clauses within the try statement. When Python runs the try clause there are three possibilities 1), 2a) or 2b):
1) If there is no exception, the try clause is completed and all the except clauses are skipped.
2) If an exception thrown in the try clause, the remaining statements in the try clause are skipped. Python matches the thrown exception with the named exception(s) after each except:
2a) If the exception matches any named exception, only that except clause  is run (and all the other except clauses are skipped).
2b) If the exception does not match any named exception in any except, the Python script execution stops with an error message. In order to catch any unnamed exception, we can have the last except without any named exceptions (as in the Python code examples below).

December 12, 2019

Python tutorial 14 | File handling | Working with files

Moving on to the next tutorial in the Python Tutorials for Beginners. This Python beginner tutorial explains how to work with files. Please view the Python video tutorial 14 or read on...Let us learn how to work with text files in Python programming. The syntax for opening a file with the open function is: file = open (file_name, mode)

In the above syntax, the mode is optional. If the mode is not specified or specified as 'r', the file will open in the read mode. If the mode is specified as 'a', the file will open in the append mode (meaning we can add text after existing text in the file). If the mode is specified as 'r+', the file will open in the read-write mode (meaning that we can read from the file and write to it). If the mode is specified as 'w', the file will open in the write mode (meaning that the existing text will be erased, so we have to backup the text and be careful).

Now, let us see the file functions' syntax.
file_name.read (n bytes) - read n bytes from the file into the memory
file_name.read() - read the whole file into the memory
file_name.readline() - read one line from the file
file_name.readlines() - read all lines from the file into a list
file_name.write (string) - write a string to the file (and return the number of characters written)
file.close - close the file (end the system connection to the file)

Now, let us see Python examples of file functions.

December 01, 2019

Python tutorial 13 | List functions

Moving on to the next tutorial in Python Tutorials for Beginners. This Python beginner tutorial is the next part of the Python tutorial 12 | Lists. This tutorial explains many Python list functions with examples. Please view the Python video tutorial 12 and Python video tutorial 13. Or read on...

Let us learn about list functions in Python programming with code examples. The Python list functions are explained as comments (starting with the # symbol in the Python code below). These list functions work on Python lists with different data types (integers, floats or strings), as appropriate.

# Python code examples
# create a list of strings
vowels = ['a', 'e', 'i', 'o', 'u']

# len function returns the number of items in a Python list
# print 5, which is the number of items in the vowels list
print (len(vowels))

# min function returns the smallest item in a Python list
# print 'a', which is the smallest item in the list
print (min(vowels))

# max function returns the largest item in a Python list
# print 'u', which is the largest item in the list
print (max(vowels))

# index list function returns the index of a specific item in a list; indexes start from 0
# print 1, which is the index of item, 'e' in the list
print (vowels.index('e'))

# count list function returns the number of occurrences of a specific item in a list
# print 1, which is the number of times 'i' appears in the list
print (vowels.count('i'))


November 24, 2019

Python tutorial 12 | Lists

Let us move to the next tutorial in the Python Tutorials for Beginners. This Python beginner tutorial explains lists in Python. The tutorial also shows a variety of operations that we can do on Python lists.

What are lists? In Python programming, a list is a group of values. These values are called items. The items are commonly of the same data type like all integers or all floats. But, it is possible for the items to be of different list data types like strings, integers or floats. Lists are mutable, meaning that we can change a list. A list may have another list as an item. The lists which are items of another list are called nested lists. The list syntax is:

[item0, item1, item2,..., itemn]

In the above list format, note that the list is put between square brackets [ and ]. Within the list, the items are separated by commas. The item indexes start from 0. Now, let us see Python list examples and list operations with Python examples.

November 10, 2019

Python tutorial 11 | user defined functions

Moving on with Python Tutorials for Beginners. This Python beginner tutorial explains how to write user-defined functions in Python programming with examples. Please view the Python video tutorial 11 or read on...

Functions allow us to avoid code repetition. We already know about string functions like lower, upper and capitalize and math functions like ceil, floor and trunc. We can define our own functions (called user-defined functions) in Python programming language.

A Python user defined function may have one or more parameters. The function parameters provide data to the function code. The function may produce different outputs based on the parameter values it receives in the function call. A Python user-defined functions may have documentation that explains it. The function definition syntax is:

def function_name (parameters):
    doc string
    code block
    return return_value

Note the def keyword that we use to define the function. The parameters are optional. The function body has the documentation string (the doc string), code block and the return statement. Now, let us see Python function examples.

November 03, 2019

Python tutorial 10 | numeric operations and functions

Moving on with Python Tutorials for Beginners. This Python beginner tutorial explains the useful Python numeric operations and functions with examples. It also explains how to import modules in our code. Please view the Python video tutorial 10 or read on...

First, let us see Python examples of numeric operations in Python programming.

# Python code example
i = -10
# print absolute value of i, which is 10
print (abs(i))

# use max numeric operation
# print the maximum value from a number of values, which is 100
print (max(-1, 100, 2.3, 4, 90))

# use min numeric operation
# print the minimum value from a number of values, which is -1
print (min(-1, 100, 2.3, 4, 90))

# use round numeric operation
a = 1.234
# print the float value rounded off to the nearest integer value
print (round(a))
# print the float value rounded off to 2 decimal places
print (round(a, 2))

October 28, 2019

Python tutorial 9 | string methods

Let us continue with Python Tutorials for Beginners. If you are new to Python strings, please see my Python tutorial 2 | Handling Strings first. This Python beginner tutorial explains many useful Python string functions with examples. Please view the Python video tutorial 9 or read on...

Now let us see Python examples of string methods in Python programming.

# Python code example
greeting = "Hello"

# print in lower case
print (greeting.lower())

# print in upper case
print (greeting.upper())

name = 'john doe'
# print only the first character in capitals with capitalize
print (name.capitalize())

# print the first character capitalized in every word with title
print (name.title())

# Python code example
some_string = "   this is some text   "
# strip the left hand side spaces with lstrip
print (some_string.lstrip())
# strip the given left hand side characters i.e. spaces, t and h with lstrip
print (some_string.lstrip(' th'))
# strip the right hand side spaces with rstrip
print (some_string.rstrip())
# strip the given right hand side characters i.e. t and spaces with rstrip
print (some_string.rstrip('t '))
# strip spaces on both ends with strip
print (some_string.strip())

October 13, 2019

Python tutorial 8 | for loop statement

This is the next of Python Tutorials for Beginners. Please view all the Python tutorials in this blog here. This Python beginner tutorial explains the for statement in Python with multiple examples. The Python for statement loops over items of any sequence like an integer series or a list. Please view the Python video tutorial 8 or read on...

In Python programming, it is simple to create the sequence of integers that you need by using the range function. You can use the continue statement or break statement in the for loop. As in the while loop, the continue statement skips the current iteration of the for loop. The break statement ends the for loop immediately.

The for statements in Python programming have the Python for loop syntax below. The variable is assigned the first value in the sequence and the code block1 (for block) is run. Then the variable is assigned the second value in the sequence and the code block1 is run again. This goes on until the sequence is complete. Then the code block2 (else block) is run once and the entire for loop statement ends. Note that the else part of the for statement is optional.

for variable(s) in sequence:
    code block1
else:
    code block2

Now, let us see Python examples of Python for loop programs.

# Python code example
# print integers from range(6) i.e. 0 through 5
# i is the Python for loop index
for i in range (6):
    print (i)
else:
    print ('End of Python for statement')

# Python code example
# print integers from the range(6) but exclude 3 i.e. 0, 1, 2, 4, 5
for i in range (6):
    if i == 3:
        continue # skip current iteration of the loop
    print (i)
else:
    print ('End of for statement')

# Python code example
# print integers from the range(6) but up to 2 i.e. 0, 1, 2
for i in range (6):
    if i == 3:
        # terminate the for loop immediately
        # even the else block (code block2) is not run
        break
    print (i)
else:
    print ('End of for statement')

October 06, 2019

Python tutorial 7 | while statement

This is the next of Python Tutorials for Beginners. You can see the other Python tutorials in this blog here. This Python beginner tutorial explains the while statement in Python with multiple examples. The while statement repeats execution of a code block for as long as a condition is True. Please view the Python video tutorial 7 or read on...

The while statements in Python programming have two formats, the while statement and the while else statement. Now, let us see these formats with Python examples. Note : the formats are followed by Python samples

In the first format of Python while statement, the condition is evaluated. If the condition is True, the code block is run. Again, the condition is evaluated. If the condition is still True, the code block is run again. This goes on until the condition becomes False (by some code in the code block). The while statement ends when the condition becomes False.

while condition:
    code block

# Python code example
# print integers from 1 to 5
i = 1
while i <= 5:
    print (i)
    i = i + 1 # add 1 to the value of i and assign it back to i (in other words, increase i's value by 1)

September 29, 2019

Python tutorial 6 | if statement

This is the sixth of Python Tutorials for Beginners. You can see the other Python tutorials in this blog here. This Python beginner tutorial explains the if statement in Python with multiple examples. You can use the if statement to run a block of code depending on a condition. You can write a Python condition using Python comparison operators or Python logical operators. Please view the Python video tutorial 6 or read on...

In Python programming language, the block of code is formed by indenting it by a few spaces, typically 4 spaces. The if statements in Python programming have three formats, the if statement, the if else statement and the if elif else statement. Now let us see these formats with Python examples.

Note : the formats are followed by Python samples

In the first format, the condition is evaluated. If the condition is True, then the code block is run by Python. If the condition is False, nothing happens.

if condition:
    code block

# Python code example
# input function request a string from the user
name = input('Enter a name : ')
# len function returns the length of the string, name
if len(name) > 5:
    print(name, ' has the length', len(name))

September 22, 2019

Python tutorial 5 | Logical Operators

This is the fifth of Python Tutorials for Beginners. You can see the other Python tutorials in this blog here. This Python beginner tutorial explains logical operations in Python with examples. It also shows operator precedence within logical operators and between Python comparison operators and Python logical operators. Please view the Python video tutorial 5 or read on...

Python programming language has three logical operators. The logical operators in Python are not operator, and operator and or operator. Now, there are two Boolean values, which are True and False.

The not operator results in the other Boolean value. If a condition is True, the not operator converts it to False. If the condition is False, the not operator converts it to True. The and operator needs two conditions. If both the conditions are True, the and operator gives the result as True. Else, the and operator gives the result as False. The or operator also needs two conditions. If both the conditions are False, the or operator gives the result as False. Else, the or operator gives the result as True. If a logical expression has multiple operators, the Python logical operators have different operator precedence. The not operator has the highest priority, then the and operator and finally, the or operator.

Now, let us see these logical operators with examples.

September 15, 2019

Python tutorial 4 | Comparison Operators

This is the fourth of Python Tutorials for Beginners. You can see all the Python tutorials in this blog here. This Python beginner tutorial explains comparison operations in Python programming with multiple examples. Please view my Python video tutorial 4 or read on...

You can use Python comparison operators when you write conditions in Python if statement or Python while loop statement. In Python programming language, the comparison operators include equal to, not equal to, less than, less than or equal to, greater than and greater than or equal to. The result of any Python comparison operation is a True or False value.

A single Python condition may contain different comparison operators but all comparison operators in Python have the same priority. This means that there is no operator precedence.
Now, let us see these comparison operators with examples.

September 09, 2019

Python tutorial 3 | Arithmetic Operators

This is the third of Python Tutorials for Beginners. In order to get started, you can see Python Tutorial 1 | Introduction and Python tutorial 2 | Handling Strings. Let us learn about arithmetic operators in Python programming language. This tutorial explains the arithmetic operators in Python programming. Please view my Python video tutorial 3 or read on...

What is an operator? It is a construct for processing one or more data values. In Python programming language, an operator is shown by a special character or a keyword.

There are several arithmetic operators in Python. These are + for addition, - for subtraction, * for multiplication, / for division, // for floor division or integer division, % for remainder of integer division and ** for power. Now, let us see examples of integer add, float add, integer subtract, float subtract, integer multiply, float multiply, division, floor division, remainder and power arithmetic operations in Python.

September 01, 2019

Python tutorial 2 | Handling Strings

This is the second of Python Tutorials for Beginners. In order to get started, please first see the Python Tutorial 1 | Introduction. Let us learn how to handle strings in Python programming language. Please view my Python video tutorial 2 or read on...

A string is a sequence of characters. A string is enclosed by single quotes or double quotes. A multi-line string is enclosed by triple quotes (either both single quotes or both double quotes). You can see your string by using the print function. The print function omits enclosing quotes. The + Python string operator concatenates (combines) strings. The * Python string operator repeats a string a number of times. You can assign multiple variables in a single Python statement. Using indexing, you can extract a single character from a string. Using slicing, you can extract any part of a string. Strings in Python programming language are immutable. This means that once you define a string, you cannot change it. Now, let us see examples of these concepts.

August 01, 2019

SoapUI Plugins

This is the last of my SoapUI testing tutorials. This SoapUI tutorial for beginners is on SoapUI Plugins in SoapUI tool. There is SoapUI Eclipse plugin. It gives you the SoapUI features in the Eclipse IDE (Integrated Development Environment). The Soap UI Eclipse plugin supports inspection, invoking, mocking, development and functional and other types of software testing of SOAP web services and REST web services over HTTP. It is useful for software testers who do SoapUI testing of web services. View my tutorial on SoapUI plugins to see SoapUI Eclipse plugin download, install and SoapUI Eclipse plug in working. Or read on...