webdriver --> it is a tool or module which automates the browser or web application
[Link]() --> to customize the browser
r --> raw string
By--> class object --> which contains all the locators
Name --> this is the attribute name
Value --> This is the attribute value
get --> is a method used to get web page
find_element() --> returns one element from the web page (method to find the web
element on the web page)
find_elements() --> returns the list of elements from the web page(method to find
the web element on the web page)
How to import
-------------
webdriver --> from selenium import webdriver
By --> from [Link] import By
Keys --> from [Link] import Keys
WebDriverWait --> from [Link] import WebDriverWait
expected_conditions --> from [Link] import expected_conditions
as EC
Select --> from [Link] import Select
ActionChains --> from [Link].action_chains import ActionChains
Service --> from [Link] import Service
ChromeDriverManager --> from webdriver_manager.chrome import ChromeDriverManager
time --> import time
Syntax for locators
-------------------
1) Id
object_name.find_element([Link], "Id attribute value")
Ex:- driver.find_element([Link], "email")
2) Name
object_name.find_element([Link], "Name attribute value")
Ex:- driver.find_element([Link], "email")
3) Class name
object name. find element([Link], "Class name attribute value")
Ex:- driver.find_element(By.Class_name, "email")
4) Link text locator
object_name.find_element([Link], "visible text")
Ex:- driver.find_element(By.Link_text, "forget password?")
5) Partial link text locator
object_name.find_element([Link], "part of visible text")
Ex:- driver.find_element(By.Partial_link_text, "et passw")
6) Tag name
object_name.find_element([Link], "Tag Name")
Ex:- driver.find_element(By.Tag_Name, "input")
7) CSS selector
1) CSS selector by using attribute
object_name.find_element([Link], "tag name[attribute name = 'attribute
value']")
Ex:- driver.find_element(By.CSS_Selector, "input[id='email']
2) CSS selector by using Id
object_name.find_element(By.CSS_selector, "tag name# Id attribute value")
Ex:- driver.find_element(By.CSS_selector, "input#email")
3) CSS selector by using class name
object_name.find_element(By.CSS_Selector, "tag name. Class name attribute
value")
Ex:- driver.find_element(By.CSS_Selector, "[Link].34button")
4) CSS selector by child (1st child of the parent)
object_name.find_element(By.CSS_selector, "[Link] element expression
> tagname. child element expression") -->(tagname. id attribute name >
[Link] attribute value)
Ex:- driver.find_element(By.CSS_selector, "div#id > input#email") or
(By.CSS_selector, "div.class_name > [Link].98box")
5) CSS selector by Next sibling
object_name.find_element([Link], "[Link] element expression
> child1 + child2 + child3 + child4 # attribute value") --> (input#id
attribute value > div + label + input# id attribute value)
Ex:- driver.find_element(By.CSS_SELECTOR,
"div#loginform>input+input+input+input+input+input+input+input+input+input+div>inpu
t#email")
6) CSS selector by descendant
object_name.find_element([Link], "[Link] element expression
(space) [Link] element expression")
Ex:- driver.find_element([Link], "div#id input#email")
7) CSS selector by Substring
1) Prefix(^)--> Starting part --> object_name.find_element([Link],
"tagname[attribute name ^= 'attribute value']")
2) Suffix($)--> Ending part --> object_name.find_element([Link],
"tagname[attribute name $= 'attribute value']")
3) Substring(*)--> Any part --> object_name.find_element([Link],
"tagname[attribute name *= 'attribute value']")
Ex1:- driver.find_element([Link], "input[id^='email']
Ex2:- driver.find_element([Link], "input[name$='password']")
Ex3:- driver.find_element([Link], "input[id*='login_button']")
8) CSS by Specific Mateches
1) First Child --> div#loginform input:first-child
2) Last Child --> div#loginform input:last-child
3) nth-of-type(n) --> div.login_form_container div:nth-of-type(1),
div.login_form_container input:nth-of-type(1), div.login_form_container a:nth-of-
type(1)
4) nth-child(n) --> div.login_form_container div:nth-child(1),
div.login_form_container input:nth-child(1)
8) Xpath
1) Absolute Xpath
object_name.find_element([Link],
"/tagname/tagname/tagname/tagname/tagname")
Ex:- driver.find_element([Link], "/html/body/div/div[2]/div[3]/input")
2) Relative Xpath
1) Relative Xpath attribute
object_name.find_element([Link], "//tagname[@attribute name =
'attribute value']")
Ex:- driver.find_element([Link], "//input[@name='email']")
2) Xpath by text() function -->(we use this function only to perform on
links)
object_name.find_element([Link], "//tagname[text()='visible text']")
Ex:- driver.find_element([Link], "//a[text()='Forget password?']")
3) Xpath by Normalize-space
1) object_name.find_element([Link], "//tagname[normalize-
space(text())='visible text']") -->(by using xpath by text())
2) object_name.find_element([Link], "//tagname[normalize-
space(@attribute name) = 'attribute value']") --> (by using xpath attribute(@))
Ex1:- driver.find_element([Link], "//a[normalize-
space(text())='Forgotten account?']")
Ex2:- driver.find_element([Link], "//a[normalize-space(@name)='abcd']")
4) Xpath by Contains()
1) object_name.find_element([Link],
"//tagname[contains(@source,'attribute value')]") -->source means any attribute
name (by using Xpath
attribute)
Ex:- driver.find_element([Link],
"//button[contains(@id,'loginbutton')]")
2) object_name.find_element([Link],
"//tagname[contains(source,'visible text')]") --> (by using text() function)
Ex:- driver.find_element([Link], "//a[contains(text(),'facebook
Link')]")
5) Xpath by starts-with()
1) object_name.find_element([Link], "//tagname[starts-
with(@source,'attribute value')]")
Ex:- driver.find_element([Link], "//input[starts-
with(@name,'email')]") --> (source means any attribute name)
2) object_name.find_element([Link], "//tagname[starts-
with(text(),'visible text')"])
Ex:- driver.find_element([Link], "//a[starts-with(text(),'Contact
uplo')]") -->(by using text() function)
6) Xpath by Traversing
1) Forward Traversing (Parent to child)
object_name.find_element([Link],
"//tagname/tagname[@attribute_name = attribute_value]") -->(by using xpath
attribute)(/--> for 1st child)
([Link],
"//tagname//tagname[@attribute_name = attribute_value]") -->(// --> for siblings or
grand child)
Ex:- driver.find_element([Link], "//div/input[@id='email']")
2) Backward Traversing (child to parent)
1) by using []
object_name.find_element([Link], "//grand parent tagname[parent
tagname[tagname[@attribute name = attribute value]]]//child
tagname[@attribute_name = attribute_value")
Ex:- driver.find_element([Link],
"//div[div[input[@name='email']]]//input[@name='email']")
2) by using /..
object_name.find_element([Link], "//tagname[@attribute_name =
attribure_value]/../../..//tagname[@attribute_name = attribute_value]")
Ex:- driver.find_element([Link],
"//input[@id='email']/../..//input[@id='email']")
7) Xpath by dependant and independant
object_name.find_element([Link], "//tagname[text()="link
text"]/../..//parent tagname/child tagname")
Ex:- driver.find_element([Link], "//a[text()='$5 Virtual Gift
Card']/../../div[3]/span")
8) Xpath by Group by Index
object_name.find_element([Link], "(//tagname[@attribute name =
attribute value])[index number]")
Ex:- driver.find_element([Link], "(//input[@type='radio'])[1]")
9) Xpath by Axes Functions
1) Forward
1) Child --> //div[@class="login_form_container"]//child::div,
//div[@class="login_form_container"]//child::input
2) following --> //div[@class="clearfix _5466 _44mg"]//following::input,
//div[@class="clearfix _5466 _44mg"]//following::a
3) descendant --> //div[@id="loginform"]//descendant::input,
//div[@id="loginform"]//descendant::div
4) descendant-or-self --> //div[@id="loginform"]//descendant-or-
self::div
5) following sibling --> //div[@id="loginform"]/following-sibling::input
2) Backward
1) preceding --> //div[@id="loginform"]//preceding::div
2) parent --> //div[@id="loginform"]//parent::div
3) ancestor --> //div[@class="login_form_container"]//ancestor::div
Browser commands
----------------
1) [Link]() --> which is used to navigate the url of web page
2) driver.maximize_window() --> which is used to maximize the window
3) driver.minimize_window() --> which is used to minimize the window
4) [Link] --> which is to get the title of the webpage
5) [Link]() --> which is use to navigate the back button on the web page
6) [Link]() --> which is use to navigate the forward button on the web page
7) [Link]() --> which is use to navigete the refresh button on the web page
8) driver.set_window_size(height=100, width=100) --> which is used to set the
window size of the webpage on screen
9) driver.set_window_position(x=100, y=100) --> which is used to set the window
posotin of the webpage on screen
10) driver.set_window_rect(x=100,y=100,height=100,width=100) --> which is used to
set both size and position of the window on the screen
11) [Link]() --> which is used to close the window after the execution
12) variable.is_selected() --> it will give you true if radio button is selected
(before this you should assign to a varibale)
13) variable.is_enabled() --> it will give tou true if radio button is enabled for
user (before this you should assign to a varibale)
14) [Link]() --> which is used to clear the entered text in the text field
15) is_displayed() --> which is used to check whether the image is displayed or not
16) [Link] --> which is used to get size of the image present on the screen
17) [Link] --> which is used to get position of the image present on the
screen
18) [Link] --> which is used to get both size and position of the image
present on the screen
19) [Link] --> which is used to get text of the link
#write a program to extract link with the link text
20) variable.get_attribute('attribute_name') --> which is used to get the link of
the link text
21) [Link]() --> which is used to close the entire the browser
find_elements() or multiple_elements()
--------------------------------------
find_elements() --> returns list of web elements from webpage
Synchronization
---------------
1) Unconditional Synchronization
time
--> Ex:- [Link](10)
2) conditional Synchrionization
1) implicit wait
Ex:- implicity_wait(sec)
2) explicit wait
syntax:- object = WebDriverWait(Webdriver reference obj, sec)
Ex:- wait = WebDriverWait(driver, 20)
[Link](EC.element_to_be_clickable(driver.find_element([Link], "pass")))
ask for backup
--------------
1) implicit and explicit
2) keys
3) conditonal
4) iframes
5) Cookies
Dropdown
--------
there are 3 ways to select dropdown web element
1) select_by_value("value")
2) select_by_index(index position)
3) select_by_sisible_text("text")
how to import:- from [Link] import Select
to use this we have to create one object:-
Syntax--> object = Select(object)
Ex:- sel = Select(dropdown)
sel.select_by_value("Volvo")
sel.select_by_visible_text("Suv500")
sel.select_by_index(0)
Listbox
-------
there are 3 ways to select listbox web element
1) select_by_value("value")
2) select_by_index(index position)
3) select_by_sisible_text("text")
how to import Select:- from [Link] import Select
to use this we have to create one object:-
Syntax--> object = Select(object)
Ex:- sel = Select(listbox)
sel.select_by_value("Banana")
sel.select_by_visible_text("Apple")
sel.select_by_index(5)
how to deselect --> sel.deselect_by_value("Banana")
sel.deselect_by_visible_text("Apple")
sel.deselect_by_index(3)
-->how to print all the options which is present in the list box
syntax --> variable = [Link]
Ex:- all = [Link]
for i in all:
print([Link])
-->how to print seleceted options in the list box
Syntax --> variable = object.all_selected_options
Ex:- all = sel.all_selected_options
for i in all:
print([Link])
--> how to print 1st selected option in the list box
Syntax:- variable = object.first_selected_option
Ex:- first = sel.first_selected_option
print([Link])
Action Chains
-------------
how to import ActionChains --> from [Link].action_chains import
ActionChains
1) Mouse hover --> object = ActionChains(driver)
Ex:- Action = ActionChains(driver)
fashion = driver.find_element([Link],
"//span[text()='Fashion']")
Action.move_to_element(fashion)
[Link]()
2) Mouse left click --> object = ActionChains(driver)
Ex:- food = driver.find_element([Link], "//a[text()='Food
& Drinks']")
Action.move_to_element(food)
[Link]().perform()
3) Mouse right click --> object = ActionChains(driver)
Ex:- kitchen = driver.find_element([Link],
"//a[text()='Kitchen & Dining']")
Action.move_to_element(kitchen)
Action.context_click().perform()
4) Drag & Drop --> for iframe:-
object_name.switch_to.frame(variable)
Ex:- frame = driver.find_element(By.TAG_NAME, "iframe")
driver.switch_to.frame(frame)
fro drag and drop:-
object = ActionChains(driver)
Ex:- drag = driver.find_element([Link], "draggable")
drop = driver.find_element([Link], "droppable")
Action.drag_and_drop(drag,drop).perform()
Pop-Up/Alerts
--------------------
1) html Pop-Up:- it can locate but we cannot move or close
(here we can locate dynamic webelements by using independant and dependant)
(and also we use format string while finding the webelements)
Ex: - month = 'April 2025' (we use this as dynamic web element)
date = '29'
driver.find_element([Link],
f"//div[text()='{month}']/../..//p[text()='{date}']").click()
2) non-html-popup:- it cannot locate but we can move
to locate this we use Alert class
Ex:-1) accept():- driver.switch_to.[Link]() --> it is used to click on
"OK" button
2) dismiss():- driver.switch_to.[Link]() --> it is used to click of
"CANCEL" button
3) text:- driver.switch_to.[Link]:- --> it will display the text
4) send_keys():- driver.switch_to.alert.send_keys() --> it is used to send
inputs to popups/alerts
1) Simple alert:- simple alert i.e it will having only one option i.e "ok"
button
2) Confirmation alert:- this alert will having only 2 options i.e. "ok" and
"cancel" button
3) Prompt alert:- this alert asks for some input from the user.
Screenshot
----------
syntax:-
--------
object_name.save_screenshot(path)
object_name.get_screenshot_as_file(path)
object_name.get_screenshot_as_png()
Ex:-
----
driver.save_screenshot(r"C:\Users\Kiran M\PycharmProjects\SeleniumProject\
[Link]")
driver.get_screenshot_as_file(r"C:\Users\Kiran M\PycharmProjects\SeleniumProject\
[Link]")
driver.get_screenshot_as_png()
Handling multiple windows
-------------------------
syntax:- object = object_name.window_handles
object_name.switch_to.window(objec[index_no])
Ex:- handles = driver.window_handles
driver.switch_to.window(handles[1])
Data Driven Testing(DDT)
------------------------
1) Normal DDT Test
---------------
Ex:- config = {}
with open("[Link]", 'r') as file:
for i in file:
i = [Link]()
if "=" in i:
key, value = [Link]("=", 1)
config[[Link]()] = [Link]()
2) DDT Properties
--------------
Ex:-
test = [Link]()
[Link]("[Link]")
browser = test["default"]["browser"]
url = test["default"]["url"]
timeout = [Link]("default", "timeout")
users = [(test[f"user{i}"]["username"],test[f"user{i}"]["password"]) for i in
range(1,4)]
driver = [Link](service=Service(ChromeDriverManager().install()))
[Link](url)
driver.maximize_window()
[Link](timeout)
for username, password in users:
3) DDT CSV
-------
Ex:-
with open("[Link]", "r")as file:
data = list([Link](file))
browser, url, timeout = data[1][0], data[1][1], int(data[1][2])
users = data[3:]
print(browser, url, time)
print(users)
driver = [Link](service=Service(ChromeDriverManager().install()))
[Link](url)
driver.maximize_window()
[Link](timeout)
for username, password in users:
4) DDT JSON
--------
Ex:-
with open("[Link]", "r") as file:
data = [Link](file)
browser = data["browser"]
url = data["url"]
timeout = data["timeout"]
#print(browser, url, timeout)
user = data["users"]
# print(user)
driver = [Link](service=Service(ChromeDriverManager().install()))
[Link](url)
driver.maximize_window()
[Link](timeout)
for users in user:
5) DDT Excel
---------
Ex:-
workbook = openpyxl.load_workbook("[Link]")
browser = workbook["browser"]
url = browser["B3"].value
timeout = browser["B4"].value
print(url, timeout)
users = workbook["user"]
data = [(users[f"A{i}"].value, users[f"B{i}"].value) for i in range(2,
users.max_row+1)]
print(data)
driver = [Link](service=Service(ChromeDriverManager().install()))
[Link](url)
driver.maximize_window()
[Link](timeout)
for username, password in data:
PyTest
------
commands to run the program:
----------------------------
1) pytest --> used to run the python file in terminal and it will display failed
test cases
2) pytest -v --> it will display both passed and failed test cases(v-->verbosity)
3) pytest -v -s --> it will display both passed and failed test cases along with
print statement
4) pytest -x --> it will stop executing till 1st test case fail
5) pytest -x -v -s --> it will print both passed and failed test cased until first
test case failed
5) pytest --maxfail=2 --> it will stop after 2 test cases failed
6) pytest (file name)test_day2.py --> it will allow us to excecute particular file
or selected file
7) pytest (filename::testcasename)pytest day1_test.py::test_fourth() --> it will
allow us to test only one particular test case
8) pytest -k function name--> it will run multiple test cases which is having same
test case names
9) pip install pytest-html --> to install the html plugins
10) pytest --html="filename".html --> to generate html report
Marker --> also called as decorators
------
to group the test cases we use marker or create marker
there are 2 types of markers:-
1)User defined marker
2)Built-In Marker marker
1) user defined marker
----------------------
syntax:-
--------
to create:- @[Link]
Ex:- @[Link]
to run:- @pytest -m markername
Ex:- @pytest -m functional
2) Built-In Marker
------------------
@[Link]
@[Link]
@[Link]
Ex:-
class TestCalculator:
a = 10
b = 5
@[Link](reason = "add method is working fine")
def test_add(self):
assert self.a+self.b != 0, "is equal to zero"
@[Link](b==0, reason="denominator should not be zero")
def test_div(self):
assert self.a/self.b
@[Link](reason = "result will be 5")
def test_sub(self):
assert self.a-self.b == 3, "the result is not equal 5"
Custom_markers
--------------
Ex:-
class TestCalculator:
a = 10
b = 20
@[Link].group_a
def test_add(self):
assert self.a+self.b <100, "is greater than 100"
@[Link].group_b
def test_sub(self):
assert self.a-self.b ==0, "is not equal to zero"
@[Link].group_a
@[Link].group_b
@[Link].group_c
def test_mul(self):
assert self.a*self.b == 200, "is not equal to 200"
@[Link].group_b
@[Link].group_c
@[Link].group_d
def test_div(self):
assert self.a/self.b == 0, "is not equal to zero"
Parameterize
------------
Ex1:-
@[Link]("nums", [10,20,30])
def test_cal(nums):
assert nums-10 == 0, "is not equal to zero"
Ex2:-
@[Link]("x,y", [(10,30),(20,40),(20,20),(70,50)])
def test_nums(x,y):
print(f"x = {x}, y = {y}")
assert x+y==40, "is not equal to 40"
Ex3:-
@[Link]("x,y,z", ("hil", "kil", "jil"))
def test_string(x,y,z):
print(f"x={x}, y={y}, x={z}")
Dependency
----------
how to install --> pip install pytest-dependency
Ex:-
@[Link]
def test_login():
assert True
@[Link](depends=["test_login"])
def test_add_to_cart():
assert True
@[Link](depends=["test_add_to_cart"])
def test_checkout():
assert True
Order
-----
how to install --> pip install pytest-order
Ex1:-
@[Link](3)
def test_checkout():
assert True
@[Link](1)
def test_login():
assert False
@[Link](2)
def test_add_to_cart():
assert False
Ex2:-
@[Link](depends=["test_login"])
@[Link](3)
def test_checkout():
assert True
@[Link](1)
def test_login():
assert False
@[Link](2)
def test_add_to_cart():
assert True
Fixtures
--------
1)setup
2)teardown
Ex:-
[Link]()
def setup():
print("open the browser")
print("launch the webpage")
print("maximize window")
yield
print("click on login")
print("close the browser")
def test_login_01(setup):
print("actual test case with valid username and password")
def test_login_02(setup):
print("actual test case with valid username and invalid password")
def test_login_03(setup):
print("actual test case with invalid username and valid password")
def test_login_04(setup):
print("actual test case with invalid username and password")
Autouse fixtures
----------------
Ex:-
@[Link](autouse=True)
def setup():
print("open the browser")
print("launch the webpage")
print("maximize window")
yield
print("click on login")
print("close the browser")
def test_login_01():
print("actual test case with valid username and password")
def test_login_02():
print("actual test case with valid username and invalid password")
def test_login_03():
print("actual test case with invalid username and valid password")
def test_login_04():
print("actual test case with invalid username and password")
Scope fixtures -- scope="module"
--------------------------------
Ex:-
@[Link](scope="module")
def setup():
print("open the browser")
print("launch the webpage")
print("maximize window")
yield
print("click on login")
print("close the browser")
@[Link]("setup")
def test_login_01():
print("actual test case with valid username and password")
def test_login_02():
print("actual test case with valid username and invalid password")
def test_login_03():
print("actual test case with invalid username and valid password")
def test_login_04():
print("actual test case with invalid username and password")
Scope fixtures -- scope = "class"
---------------------------------
Ex:-
@[Link](scope="class")
def setup():
print("open the browser")
print("launch the webpage")
print("maximize window")
yield
print("click on login")
print("close the browser")
@[Link]("setup")
class TestCase:
def test_login_01(self):
print("actual test case with valid username and password")
def test_login_02(self):
print("actual test case with valid username and invalid password")
def test_login_03(self):
print("actual test case with invalid username and valid password")
def test_login_04(setup):
print("actual test case with invalid username and password")
Scope fixtures == scope = "function"
-----------------------------------
Ex:-
@[Link](scope="function")
def setup():
print("open the browser")
print("launch the webpage")
print("maximize window")
yield
print("click on login")
print("close the browser")
@[Link]("setup")
def test_login_01():
print("actual test case with valid username and password")
@[Link]("setup")
def test_login_02():
print("actual test case with valid username and invalid password")
def test_login_03():
print("actual test case with invalid username and valid password")
def test_login_04():
print("actual test case with invalid username and password")
# what is import
# what is relative import:- we describe the path from the root, it will include
full address of the url
# what is abselute import:- we describe the path with respect to the current file
# difference between relative and abselute import
# why using abselute path
important topics to know
------------------------
dictionaries
for loop
complete oops concepts
class
file handling
exception handling
comprehensions
decorators