webdriver --> it is a tool or module which automates the browser or web application
chrome.options() --> 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 selenium.webdriver.common.by import By
Keys --> from selenium.webdriver.keys import Keys
WebDriverWait --> from selenium.webdriver.support.wait import WebDriverWait
expected_conditions --> from selenium.webdriver.support import expected_conditions
as EC
Select --> from selenium.webdriver.support.select import Select
ActionChains --> from selenium.webdriver.common.action_chains import ActionChains
Service --> from selenium.webdriver.chrome.service import Service
ChromeDriverManager --> from webdriver_manager.chrome import ChromeDriverManager
time --> import time
Syntax for locators
-------------------
1) Id
object_name.find_element(By.Locator, "Id attribute value")
Ex:- driver.find_element(By.Id, "email")
2) Name
object_name.find_element(By.Locator, "Name attribute value")
Ex:- driver.find_element(By.Name, "email")
3) Class name
object name. find element(By.Locator, "Class name attribute value")
Ex:- driver.find_element(By.Class_name, "email")
4) Link text locator
object_name.find_element(By.Locator, "visible text")
Ex:- driver.find_element(By.Link_text, "forget password?")
5) Partial link text locator
object_name.find_element(By.Locator, "part of visible text")
Ex:- driver.find_element(By.Partial_link_text, "et passw")
6) Tag name
object_name.find_element(By.Locator, "Tag Name")
Ex:- driver.find_element(By.Tag_Name, "input")
7) CSS selector
1) CSS selector by using attribute
object_name.find_element(By.locator, "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, "input.search.34button")
4) CSS selector by child (1st child of the parent)
object_name.find_element(By.CSS_selector, "tagname.parent element expression
> tagname. child element expression") -->(tagname. id attribute name >
tagname.id attribute value)
Ex:- driver.find_element(By.CSS_selector, "div#id > input#email") or
(By.CSS_selector, "div.class_name > input.search.98box")
5) CSS selector by Next sibling
object_name.find_element(By.CSS.selector, "tagname.parent 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(By.CSS.selector, "tagname.parent element expression
(space) tagname.child element expression")
Ex:- driver.find_element(By.CSS.selector, "div#id input#email")
7) CSS selector by Substring
1) Prefix(^)--> Starting part --> object_name.find_element(By.Locator,
"tagname[attribute name ^= 'attribute value']")
2) Suffix($)--> Ending part --> object_name.find_element(By.Locator,
"tagname[attribute name $= 'attribute value']")
3) Substring(*)--> Any part --> object_name.find_element(By.Locator,
"tagname[attribute name *= 'attribute value']")
Ex1:- driver.find_element(By.CSS.selector, "input[id^='email']
Ex2:- driver.find_element(By.CSS.selector, "input[name$='password']")
Ex3:- driver.find_element(By.CSS.selector, "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(By.Locator,
"/tagname/tagname/tagname/tagname/tagname")
Ex:- driver.find_element(By.Xpath, "/html/body/div/div[2]/div[3]/input")
2) Relative Xpath
1) Relative Xpath attribute
object_name.find_element(By.locator, "//tagname[@attribute name =
'attribute value']")
Ex:- driver.find_element(By.Xpath, "//input[@name='email']")
2) Xpath by text() function -->(we use this function only to perform on
links)
object_name.find_element(By.locator, "//tagname[text()='visible text']")
Ex:- driver.find_element(By.Xpath, "//a[text()='Forget password?']")
3) Xpath by Normalize-space
1) object_name.find_element(By.Locator, "//tagname[normalize-
space(text())='visible text']") -->(by using xpath by text())
2) object_name.find_element(By.Locator, "//tagname[normalize-
space(@attribute name) = 'attribute value']") --> (by using xpath attribute(@))
Ex1:- driver.find_element(By.XPATH, "//a[normalize-
space(text())='Forgotten account?']")
Ex2:- driver.find_element(By.XPATH, "//a[normalize-space(@name)='abcd']")
4) Xpath by Contains()
1) object_name.find_element(By.Locator,
"//tagname[contains(@source,'attribute value')]") -->source means any attribute
name (by using Xpath
attribute)
Ex:- driver.find_element(By.XPATH,
"//button[contains(@id,'loginbutton')]")
2) object_name.find_element(By.Locator,
"//tagname[contains(source,'visible text')]") --> (by using text() function)
Ex:- driver.find_element(By.XPATH, "//a[contains(text(),'facebook
Link')]")
5) Xpath by starts-with()
1) object_name.find_element(By.Locator, "//tagname[starts-
with(@source,'attribute value')]")
Ex:- driver.find_element(By.XPATH, "//input[starts-
with(@name,'email')]") --> (source means any attribute name)
2) object_name.find_element(By.Locator, "//tagname[starts-
with(text(),'visible text')"])
Ex:- driver.find_element(By.XPATH, "//a[starts-with(text(),'Contact
uplo')]") -->(by using text() function)
6) Xpath by Traversing
1) Forward Traversing (Parent to child)
object_name.find_element(By.Locator,
"//tagname/tagname[@attribute_name = attribute_value]") -->(by using xpath
attribute)(/--> for 1st child)
(By.Locator,
"//tagname//tagname[@attribute_name = attribute_value]") -->(// --> for siblings or
grand child)
Ex:- driver.find_element(By.XPATH, "//div/input[@id='email']")
2) Backward Traversing (child to parent)
1) by using []
object_name.find_element(By.Locator, "//grand parent tagname[parent
tagname[tagname[@attribute name = attribute value]]]//child
tagname[@attribute_name = attribute_value")
Ex:- driver.find_element(By.XPATH,
"//div[div[input[@name='email']]]//input[@name='email']")
2) by using /..
object_name.find_element(By.Locator, "//tagname[@attribute_name =
attribure_value]/../../..//tagname[@attribute_name = attribute_value]")
Ex:- driver.find_element(By.XPATH,
"//input[@id='email']/../..//input[@id='email']")
7) Xpath by dependant and independant
object_name.find_element(By.Locaror, "//tagname[text()="link
text"]/../..//parent tagname/child tagname")
Ex:- driver.find_element(By.XPATH, "//a[text()='$5 Virtual Gift
Card']/../../div[3]/span")
8) Xpath by Group by Index
object_name.find_element(By.Locator, "(//tagname[@attribute name =
attribute value])[index number]")
Ex:- driver.find_element(By.XPATH, "(//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) driver.get() --> 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) driver.title --> which is to get the title of the webpage
5) driver.back() --> which is use to navigate the back button on the web page
6) driver.forward() --> which is use to navigate the forward button on the web page
7) driver.refresh() --> 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) driver.close() --> 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) variable.clear() --> 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) variable.size --> which is used to get size of the image present on the screen
17) variable.location --> which is used to get position of the image present on the
screen
18) variable.rect --> which is used to get both size and position of the image
present on the screen
19) variable.text --> 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) driver.quit() --> 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:- time.sleep(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)
wait.until(EC.element_to_be_clickable(driver.find_element(By.ID, "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 selenium.webdriver.support.select 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 selenium.webdriver.support.select 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 = object.options
Ex:- all = sel.options
for i in all:
print(i.text)
-->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(i.text)
--> how to print 1st selected option in the list box
Syntax:- variable = object.first_selected_option
Ex:- first = sel.first_selected_option
print(first.text)
Action Chains
-------------
how to import ActionChains --> from selenium.webdriver.common.action_chains import
ActionChains
1) Mouse hover --> object = ActionChains(driver)
Ex:- Action = ActionChains(driver)
fashion = driver.find_element(By.XPATH,
"//span[text()='Fashion']")
Action.move_to_element(fashion)
Action.perform()
2) Mouse left click --> object = ActionChains(driver)
Ex:- food = driver.find_element(By.XPATH, "//a[text()='Food
& Drinks']")
Action.move_to_element(food)
Action.click().perform()
3) Mouse right click --> object = ActionChains(driver)
Ex:- kitchen = driver.find_element(By.XPATH,
"//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(By.ID, "draggable")
drop = driver.find_element(By.ID, "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(By.XPATH,
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.alert.accept() --> it is used to click on
"OK" button
2) dismiss():- driver.switch_to.alert.dismiss() --> it is used to click of
"CANCEL" button
3) text:- driver.switch_to.alert.text:- --> 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\
before.png")
driver.get_screenshot_as_file(r"C:\Users\Kiran M\PycharmProjects\SeleniumProject\
after.png")
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("config.properties", 'r') as file:
for i in file:
i = i.strip()
if "=" in i:
key, value = i.split("=", 1)
config[key.strip()] = value.strip()
2) DDT Properties
--------------
Ex:-
test = configparser.ConfigParser()
test.read("test.properties")
browser = test["default"]["browser"]
url = test["default"]["url"]
timeout = test.getint("default", "timeout")
users = [(test[f"user{i}"]["username"],test[f"user{i}"]["password"]) for i in
range(1,4)]
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
driver.get(url)
driver.maximize_window()
time.sleep(timeout)
for username, password in users:
3) DDT CSV
-------
Ex:-
with open("test.csv", "r")as file:
data = list(csv.reader(file))
browser, url, timeout = data[1][0], data[1][1], int(data[1][2])
users = data[3:]
print(browser, url, time)
print(users)
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
driver.get(url)
driver.maximize_window()
time.sleep(timeout)
for username, password in users:
4) DDT JSON
--------
Ex:-
with open("test.json", "r") as file:
data = json.load(file)
browser = data["browser"]
url = data["url"]
timeout = data["timeout"]
#print(browser, url, timeout)
user = data["users"]
# print(user)
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
driver.get(url)
driver.maximize_window()
time.sleep(timeout)
for users in user:
5) DDT Excel
---------
Ex:-
workbook = openpyxl.load_workbook("testxl.xlsx")
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 = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
driver.get(url)
driver.maximize_window()
time.sleep(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:- @pytest.mark.markername
Ex:- @pytest.mark.functional
to run:- @pytest -m markername
Ex:- @pytest -m functional
2) Built-In Marker
------------------
@pytest.mark.skip
@pytest.mark.skipif
@pytest.mark.xfail
Ex:-
class TestCalculator:
a = 10
b = 5
@pytest.mark.skip(reason = "add method is working fine")
def test_add(self):
assert self.a+self.b != 0, "is equal to zero"
@pytest.mark.skipif(b==0, reason="denominator should not be zero")
def test_div(self):
assert self.a/self.b
@pytest.mark.xfail(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
@pytest.mark.group_a
def test_add(self):
assert self.a+self.b <100, "is greater than 100"
@pytest.mark.group_b
def test_sub(self):
assert self.a-self.b ==0, "is not equal to zero"
@pytest.mark.group_a
@pytest.mark.group_b
@pytest.mark.group_c
def test_mul(self):
assert self.a*self.b == 200, "is not equal to 200"
@pytest.mark.group_b
@pytest.mark.group_c
@pytest.mark.group_d
def test_div(self):
assert self.a/self.b == 0, "is not equal to zero"
Parameterize
------------
Ex1:-
@pytest.mark.parametrize("nums", [10,20,30])
def test_cal(nums):
assert nums-10 == 0, "is not equal to zero"
Ex2:-
@pytest.mark.parametrize("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:-
@pytest.mark.parametrize("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:-
@pytest.mark.dependency
def test_login():
assert True
@pytest.mark.dependency(depends=["test_login"])
def test_add_to_cart():
assert True
@pytest.mark.dependency(depends=["test_add_to_cart"])
def test_checkout():
assert True
Order
-----
how to install --> pip install pytest-order
Ex1:-
@pytest.mark.order(3)
def test_checkout():
assert True
@pytest.mark.order(1)
def test_login():
assert False
@pytest.mark.order(2)
def test_add_to_cart():
assert False
Ex2:-
@pytest.mark.dependency(depends=["test_login"])
@pytest.mark.order(3)
def test_checkout():
assert True
@pytest.mark.order(1)
def test_login():
assert False
@pytest.mark.order(2)
def test_add_to_cart():
assert True
Fixtures
--------
1)setup
2)teardown
Ex:-
pytest.fixture()
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:-
@pytest.fixture(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:-
@pytest.fixture(scope="module")
def setup():
print("open the browser")
print("launch the webpage")
print("maximize window")
yield
print("click on login")
print("close the browser")
@pytest.mark.usefixtures("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:-
@pytest.fixture(scope="class")
def setup():
print("open the browser")
print("launch the webpage")
print("maximize window")
yield
print("click on login")
print("close the browser")
@pytest.mark.usefixtures("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:-
@pytest.fixture(scope="function")
def setup():
print("open the browser")
print("launch the webpage")
print("maximize window")
yield
print("click on login")
print("close the browser")
@pytest.mark.usefixtures("setup")
def test_login_01():
print("actual test case with valid username and password")
@pytest.mark.usefixtures("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