Python
Python
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
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")
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")
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']")
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
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
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")))
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")
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)
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()
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()
2) DDT Properties
--------------
Ex:-
test = configparser.ConfigParser()
test.read("test.properties")
browser = test["default"]["browser"]
url = test["default"]["url"]
timeout = test.getint("default", "timeout")
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
driver.get(url)
driver.maximize_window()
time.sleep(timeout)
3) DDT CSV
-------
Ex:-
with open("test.csv", "r")as file:
data = list(csv.reader(file))
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
driver.get(url)
driver.maximize_window()
time.sleep(timeout)
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)
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)
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
2) Built-In Marker
------------------
@pytest.mark.skip
@pytest.mark.skipif
@pytest.mark.xfail
Ex:-
class TestCalculator:
a = 10
b = 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")
@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")
@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")
@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