Python tutorial - yoss123/test-automation-repo GitHub Wiki
1. Python download (Selenium Python Tutorial #2 - How to Install Python on Windows OS)
Google "Python download", click on the button under the text "Download the latest version for Windows" and follow the custom installation steps from 3:40 in the video
2. PyCharm download & Install (Selenium Python Tutorial #4 - How to Install Pycharm on Windows)
Google "PyCharm", click the 1st result from Jetbrains, click on "Download" -> Windows -> Community, execute the downloaded exe file and continue the steps in the video from 4:00.
Make sure you're using the latest version of Python you installed in the previous step (File->Settings->Project->Python Interpreter). If not, change it by locating the Python.exe in the installed Python directory).
3. Installing Selenium in Python (Selenium Python Tutorial #5 - How to Install Selenium in Python)
To see if selenium is installed on your machine, open Command Prompt and execute the command "pip list".
To install Selenium on your machine run the command "pip install selenium" in Command Prompt.
Basically, pip is the aquivalent of the POM.xml in Maven projects in Java (it downloads the all the relevant packages for selenium).
4. Installing Selenium in PyCharm (Selenium Python Tutorial #6 - How to Install Selenium in Pycharm)
Nothing to do here ! Just make sure Selenium is installed in your PyCharm: Click on the project -> File->Settings->Project->Python Interpreter, and see that selenium is in the packages list. If not then follow the steps starting 3:40 in the video.
5. Installing KITE (AI Code AutoComplete) plugin in PyCharm (Selenium Python Tutorial #7 - How to Install Kite in Pycharm)
No need to view the video. Just click on File->Settings->Plugins->Marketplace-> search for KITE and click on INSTALL.
6. Running Selenium test with Chrome (Selenium Python Tutorial #8 - How to Run Selenium Test in Chrome)
Download webdriver from Selenium website link, extract and save it locally.
7. Using WebDriver manager in Python (Selenium Python Tutorial #11 - How to use Webdriver Manager for Python)
Simply download WedDriver manager package from PyPI using pip command and start using it in your code.
Comments: # for a line in Python vs // in Java. Also, triple quotes (""" aaa """) can be used for multiline comments vs "/** **/" in Java
Variable type: No need to declare variable type in Python
File naming conventions: file_name_in_python.py - FileNameInJava.java
String assignment: In Python you can use double quote or single quote ('), for example: x="aaa" or y='bbb'
How to know the type/class-name of a variable: print(type(x)) while x is a variable of any type/class
bool(x) : x=0 function return false ; x=10 function return true ; x="" function return false ; x="aaa" function return true
To see the full list of the String functions google "python documentation" => Library reference => Common string operations.
You can also view the full list of string functions here
len(s) - Return the length of the string
str(s) - Converts s variable to a string
str.upper() - converts a string to uppercase
str.count(sub[, start[, end]]) - how many instances of a substring is within a string between 'start' & 'end' positions (optional).
For example, if x="abcdefgabcdefgabcdefg" then x.count("a", 5,15) will return 2
str.isupper() - return true if all the characters in the string are upper case
str.islower() - return true if all the characters in the string are lower case
str.split(sep=None, maxsplit=- 1) - Return a list of the words in the string, using sep as the delimiter string
str.rsplit(sep=None, maxsplit=- 1) - behaves like split() but from the right
str.strip() - If no parameter used then trim the string from blank space at the beginning & the end of the string.
If special characters sent as parameters then remove them from the string. For example, str.strip('!$7;') then removes the characters !,$,7,; from the string.
str.lstrip([chars]) - removes any leading characters
str.rstrip([chars]) - removes any trailingcharacters
replace(old, new[, count]) - Return a copy of the string with all occurrences of substring old replaced by new
str.find(sub[, start[, end]]) - Return the lowest index in the string where substring sub is found within the slice s[start:end].
Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.
str.index(sub[, start[, end]]) - Like find(), but raise ValueError when the substring is not found.
str[startindex:endindex:step]
Example 1: If str="this is an example" then print(str[1:6:2]) will print: hsi
Example 2: If str="this is an example" then print(str[::-1]) will print the string in reverse: elpmaxe na si siht
x="Yossi"
y="Avi"
Example 1: print("My name is "+x+" and his name is "+y)
Example 2: print("My name is {0} and his name is {1}".format(x,y))
Both examples above will print the same text
In Python, we can define a list of items from different types, for example:
my_list = [1,"12",40.5,1,"str"]
print(my_list[2]) => 40.5
print(type(my_list) => <class 'list'>
print(my_list[1:3]) => ['12', 40.5]
print(my_list[1:4:2]) => ['12', 1]
list.append - Add an item to the end of the list.
list.insert - Insert an item at a given position.
list.remove- Remove the first item from the list whose value is equal to x.
list.pop - Remove the item at the given position in the list, and return it.
list.index - Return zero-based index in the list of the first item whose value is equal to x.
list.count - Return the number of times x appears in the list.
list.sort - Sort the items of the list in place.
list.reverse - Reverse the elements of the list in place.
list.copy - Return a shallow copy of the list.
list.clear - Remove all items from the list.
Set differ from List in 2 things: 1. It doesn't holds duplicate values and 2. the elements in it are not ordered.
Also, in declaration we use {} instead of [], for example:
set_sample = {10,"20",40.5}
We can also declare a Set in the next way:
set_sample_2 = set((45,"46",47,"48"))
Set will delete duplicated values of the set if declared, for example:
set_sample_3 = {10,10,20,30,20,30} ; print(set_sample_3) => {20,10,30} ; print(len(set_sample_3)) => 3 ; print(20 in set_sample_3) => true
For full list of Set methods see the documentation on Set
set_sample.issubset(other) - Test whether every element in the set_sample is in other
set_sample.issuperset(other) - Test whether every element in other is in the set.
set_sample.union(others) - Return a new set with elements from the set and all others
set_sample.intersection(others) - Return a new set with elements common to the set and all others
set_sample.difference(others) - Return a new set with elements in the set that are not in the others
set_sample.symmetric_difference(other) - Return a new set with elements in either the set or other but not both
set_sample.update(others) - Update the set, adding elements from all others
set_sample.intersection_update(others) - Update the set, removing elements found in others
add(elem) - Add element elem to the set.
remove(elem) - Remove element elem from the set. Raises KeyError if elem is not contained in the set.
discard(elem) - Remove element elem from the set if it is present.
pop() - Remove and return an arbitrary element from the set. Raises KeyError if the set is empty.
clear() - Remove all elements from the set.
Tuple are indexed, allow duplicate values and cannot be modified (immutable) - kind of immutable List. For example:
demo_tuple=(1,"2",True,3.5,44,"55",6,False)<br>A mapping object maps hashable values to arbitrary objects. Mappings are mutable objects. There is currently only one standard mapping type, the dictionary.
Examples to defined dictionaries:
demo_dict = {}
demo_dict1 = {3:12, 1:45, 2:55}
demo_dict2 = {"a":"aaa", "c":bbb", "b":"ccc"}
demo_dict3 = {'x':"dd", 2:15, 6:"rtrt", "sdk":3}Examples on how to add/change key-value pair to a dictionary:
demo_dict2['jkf']='holly'
demo_dict1[1]=60Example on hoe to remove value from a dictionary:
demo_dict2.pop("c")To review the Dictionary methods in the Python documentation click here ; To review the common used Dictionary methods watch this video
For example, executing the next code:
if(False):
print("1st true")
print("2nd true")
elif(False):
print("1st canonical false")
print("2nd canonical false")
else:
print("1st false")
print("2nd false")Will result the next output:
1st false
2nd false
The next example:
counter=0
city="Tel-Aviv"
while counter < len(city):
print(city[counter])
counter+=1
print("end of while loop")Will result:
T
e
l
The next example:
cities = [["India", "Delhi"],["Australia", "Melbourne"],["Israel", "TLV"]]
for country, city in cities:
print(country, city)Will result:
India Delhi
Australia Melbourne
Israel TLV
The Zip is a build-in function in Python that takes Iterator 1 and map it to iterator 2.
For example:
list_of_countries = ["India","USA","Australia","Israel"]
list_of_cities = ["Pune","NY","Melbourne","TLV"]
s = zip(list_of_countries,list_of_cities)
print(list(s))Will result:
[('India', 'Pune'), ('USA', 'NY'), ('Australia', 'Melbourne'), ('Israel', 'TLV')]
To read more about build-in functions in Python click here
range(start, stop[, step])
For example:
for x in range(1,10,2):
print(x)Will result:
1
3
5
7
9
To read more about build-in functions in Python click here
The next example:
def addition(x,y):
"""
This is an example for a function documentation
:param x:
:param y:
:return: The sum of the 2 int parameters passed to this function
"""
return x+y
print("The return value from addition(x,y) is: ",addition(5,4))Will result:
The return value from addition(x,y) is: 9
The next example:
def sub_demo(x=8,y=2):
return x-y
print(sub_demo(10,5))
print(sub_demo(10))
print(sub_demo())
print(sub_demo(y=1,x=0))Will result:
5
8
6
-1
The next example:
import datetime
current_date = datetime.datetime.today().date()
current_time = datetime.datetime.today().time()
current_datetime = datetime.datetime.today()
current_datetime_formated = current_datetime.strftime('%Y-%m-%d-%H-%M-%S-%f')Will result:
2022-01-28
17:45:32.883564
2022-01-28 17:45:32.883564
2022-01-28-17-45-32-883564
To learn more from the documentation about Datetime module click here
The next example: ('self' is equivalent for 'this' in Java)
class Employee:
not_self_email_example = "not_self_variable_example"
def __init__(self, fname, lname, email):
self.fname = fname
self.lname = lname
self.email = email
def greet_person(self):
print("Welcom to our company "+self.fname)
def print_not_self_variable_example(self):
print(Employee.not_self_email_example)
employee1 = Employee('Avi', 'Kalo', '[email protected]')
employee1.greet_person()
print(employee1.fname)
employee1.print_not_self_variable_example()Will result:
Welcom to our company Avi
Avi
not_self_variable_example
Click here to read more about "Access Modifiers in Python : Public, Private and Protected"
In Python there can be inheritance from multiple classes. For example:
class A:
...
class B:
...
class C(A,B):
...
The order of the inheritance in class C is from left-to-right, namely, A and then B,
Modules in Python are like packages in Java. To use elements defined in a .py file from other package (module) we need to import it using the next syntax:
from [module name] import [.py file name]
And then we can use the functions/classes/etc. from that file
The next example:
try:
print("Enter 1st number:")
x = int(input())
print("Enter 2nd value:")
y = int(input())
print(x/y)
except Exception as e:
print(e)
print("In except block")
else:
print("In else block")
finally:
print("This is always executed")Will result:
Enter 1st number:
8
Enter 2nd value:
0
division by zero
In except block
This is always executed
The next example will write to a file the list of numbers:
file_sample = open("writeExample.txt", "w")
list_of_ints = [0,1,3,5,9,10]
for item in list_of_ints:
file_sample.write(str(item)+"\n")
file_sample.close()
file_sample = open("writeExample.txt", "a")
file_sample.write("Appending new line")
file_sample.close()
file_sample = open("writeExample.txt", "r")
print(file_sample.read())
print(file_sample.readline())
file_sample.close()
with open("writeExample.txt", "a") as appender_demo_1:
appender_demo_1.write("Appending text to the file without the need to specify closing the file")
with open("writeExample.txt", "r") as appender_demo_2:
print("Reading text from the file without the need to specify closing the file")
print(appender_demo_2.read())To learn more about writing to and reading from files click here (Python->Documentation->Tutorials->Reading and writing files)
1st we need to download a package that will help us to work with Excel files. So, google "python excel" and look for a package to download. For example, this link list some packages. One of the recommended packages is openpyxl. Install it by running the command "pip install openpyxl" in the command line.
Example for writing to Excel file:
from openpyxl import Workbook
workbook_sample = Workbook()
worksheet_sample = workbook_sample.active
# test_data = [['1a','1b'],['2a','2b'],['3a','3b']]
# for data in test_data:
# worksheet_sample.append(data)
# workbook_sample.save("test_data.xlsx")
for i in range(1,4):
for j in range(1,10):
worksheet_sample.cell(row=j,column=i).value = i+j
workbook_sample.save("workbook_demo.xlsx")Example for reading from Excel file:
from openpyxl import Workbook, load_workbook
workbook_sample = load_workbook("test_data.xlsx")
worksheet_demo = workbook_sample["Sheet"]
print(worksheet_demo['A2'].value)
print(workbook_sample["Sheet"]["A2"].value)
print(worksheet_demo.cell(row=2,column=2).value)
print("\nIterating over ALL cells")
row_count = worksheet_demo.max_row
column_count = worksheet_demo.max_column
for i in range(1,row_count+1):
for j in range(1,column_count+1):
print(worksheet_demo.cell(row=i,column=j).value)1st we need to download the Faker package. So, google "python faker" and look for a package to download. Open cmd and execute "pip install Faker".
Example:
from faker import Faker
from openpyxl import Workbook
workbook_sample = Workbook()
worksheet_sample = workbook_sample.active
# fake_data = Faker()
fake_data = Faker("he_IL")
# fake_data = Faker['en_US','he_IL']
for i in range(1,10):
for j in range(1,4):
worksheet_sample.cell(row=i,column=1).value=fake_data.name()
worksheet_sample.cell(row=i, column=2).value = fake_data.email()
worksheet_sample.cell(row=i, column=3).value = fake_data.address()
workbook_sample.save("testData.xlsx")Download SelectorsHub and install it on your browser.
To use it: open devTools (F12) and on the right pane select the tab of SelectorsHub. Right click on the element in the page and select 'Inspect'. This will give you several options to locate the Web Element (xPath, CssSelector & more).
Next lesson - Python for Testers #39 - Exception Handling in Python