Python Selenium 4.x Notes - Web Automation - TheTestingAcademy - Pramod
Python Selenium 4.x Notes - Web Automation - TheTestingAcademy - Pramod
x
Notes - TheTestingAcademy (Pramod Sir)
About Selenium
What is Selenium?
Selenium RC executed tests by injecting JavaScript code into the web browser being
automated. RC deprecated.
Compare Results -
https://blog.checklyhq.com/cypress-vs-selenium-vs-playwright-vs-puppeteer-speed-comparis
on/
Don’t use Selenium here
Few situations where you might not want to use Selenium for testing.
● Selenium is not well-suited for performance or load testing because it is
resource-intensive and can slow down the system under test.
● When you need to test native mobile apps.
● Selenium may have difficulty interacting with custom controls or non-standard UI
elements.
● Captcha / TWO-FACTOR AUTHENTICATION (2FA)
● FILE DOWNLOADS & VERIFICATION.
● AUDIO OR VIDEO STREAMING
● Security Testing
● API TESTING, mobile Appium is recommended.
WebDriver Architecture
Before Selenium 4
After Selenium 4.x ( w3c)
Quick Reference
Browser Supported OS Maintained by
HTML elements
https://www.w3schools.com/html/html_elements.asp
Selenium IDE
● Open source record and playback test automation for the web
● Selenide Language
● Installation
● Launch the IDE
● Recording test
○ Suite
○ test
● Command-line Runner
● npm install -g selenium-side-runner
● npm install -g chromedriver
● npm install -g geckodriver
● Control Flow
● Code Export
capability.setBrowserName();
capability.setPlatform();
capability.setVersion()
capability.setCapability(,);
Selenium Grid 4
Run Grid 4
https://www.selenium.dev/documentation/en/grid/grid_4/setting_up_your_own_grid/
https://github.com/SeleniumHQ/docker-selenium
docker run -d -p 4444:4444 -v /dev/shm:/dev/shm
selenium/standalone-chrome:4.0.0-alpha-7-prerelease-20201009
Run on Cloud Service Providers - BrowserStack
https://www.browserstack.com/
https://www.w3.org/TR/webdriver/
https://drive.google.com/drive/folders/1tYeAaBbvE6WptutWSz_pU6DOpuaf22pp?usp=sharin
g
Virtual Env
● Isolate the Python Environments
● Main Parent - Global
○ Prject basec Python version activate or deactivate the virtualenv
● How to Install
○ Pip install virtualenv
○ Virtualenv – help
○ Optional - python -m pip install --user virtualenv
○
● Create the environment (creates a folder in your current directory)
○ virtualenv env_name
● In Linux or Mac, activate the new python environment
○ source env_name/bin/activate
● Or in Windows
○ .\env_name\Scripts\activate
● Confirm that the env is successfully selected
○ which python3
● Deactivate
○ deactivate
import logging
LOGGER = logging.getLogger(__name__)
driver.get("https://www.google.com")
LOGGER.info('eggs info')
LOGGER.warning('eggs warning')
LOGGER.error('eggs error')
LOGGER.critical('eggs critical')
Webdriver Hierarchy
WebDriver API – The API is a set of classes and methods that allow you to interact with the
browser through code. The API allows running the tests on different browsers like Chrome,
Firefox, MS Edge, etc.
API gives you access to browser controls like the navigation bar, back button, tabs, windows,
etc. You can also get information from the browser, such as the current URL and page
source.
Also, different actions like typing in a textbox and working with WebElements like
checkboxes, radio buttons, and dropdowns can be performed using WebDriver API.
ChromeDriver
The ChromeDriver class provides a number of methods for interacting with the Chrome
browser, such as get() for navigating to a specific URL, findElement() for locating elements
on a page, and click() for simulating a mouse click on an element. You can use these
methods to automate a variety of actions on the Chrome browser.
ChromeOptions
https://gist.github.com/ntamvl/4f93bbb7c9b4829c601104a2d2f91fe5
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--start-maximized")
pageLoadStrategy
Proxy
A proxy server acts as an intermediary for requests between a client and a server. In simple,
the traffic flows through the proxy server on its way to the address you requested and back.
def test_login():
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--start-maximized")
# Set PageLoadStrategy to 'none' (Not a built-in option,
# but we can use it for reference)
# Add the proxy to ChromeOptions
chrome_options.add_argument("--page-load-strategy=none")
driver = webdriver.Chrome(options=chrome_options)
driver.get("https://app.vwo.com")
print(driver.title)
driver.quit()
Remote WebDriver
Remote WebDriver consists of a server and a client. The server is a component that listens
on a port for various requests from a Remote WebDriver client.
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import
DesiredCapabilities
# Now you can interact with the web page using the specified options on
the Remote WebDriver
🧭Navigation in Selenium
● Refresh, forward, back
● driver.get()
driver.get("https://www.example.com");
navigate().to(String url) - Not Exist in python
● Refresh
● Back
● forward
# Navigation Command
driver.back()
driver.get("https://www.bing.com")
print(driver.title)
driver.forward()
print(driver.title)
driver.back()
print(driver.title)
driver.refresh()
time.sleep(5)
driver.quit( )
🔎 Locators in Selenium
A locator is a way of identifying an element on a web page so that it can be interacted with.
There are several different types of locators that can be used, including:
● ID: This locator type uses the unique ID attribute of an element to locate it on the
page.
● Name: This locator type uses the name attribute of an element to locate it on the
page.
● Class name: This locator type uses the class attribute of an element to locate it on
the page.
● Tag name: This locator type uses the HTML tag name of an element to locate it on
the page.
● Link text: This locator type uses the text of a link to locate it on the page.
● Partial link text: This locator type uses part of the text of a link to locate it on the
page.
● CSS selector: This locator type uses a CSS selector to locate an element on the
page.
● Xpath: This locator type uses an XPath expression to locate an element on the page.
● When writing test scripts with Selenium, you can use a combination of these locator
types to accurately and reliably locate elements on the page.
For multiple elements, you can use the plural versions of these functions.
● (e.g., find_elements_by_id, find_elements_by_name, etc.), which will return a list of
matching WebElement objects.
It uses "locators" to identify and manipulate elements on a web page. There are several
btn-lg">Make Appointment</a>
1. ID: This locator uses the unique id attribute of an element to locate it. For example, if
the HTML for an element on the page looks like this: <div id="some-id">...</div>, you can
use the ID locator "#some-id" to find this element.
2. Name: This locator uses the name attribute of an element to locate it. For example, if
the HTML for an element on the page looks like this: <input name="username">, you can
use the Name locator "username" to find this element.
3. Class Name: This locator uses the class attribute of an element to locate it. For
example, if the HTML for an element on the page looks like this: <div
class="some-class">...</div>, you can use the Class Name locator ".some-class" to find this
element.
4. Link Text: This locator uses the visible text of a link element to locate it. For example,
if the HTML for a link on the page looks like this: <a
href="https://app.vwo.com/">VWO</a>, you can use the Link Text locator "VWO" to find this
element.
5. Partial Link Text: This locator is similar to the Link Text locator, but it only matches a
portion of the link text. For example, using the Partial Link Text locator "VWO" would
match a link with the text "Welcome to VWO".
6. CSS Selector: This locator uses a CSS selector to locate an element. CSS selectors
are strings that specify how to find an element on a page based on its HTML
structure. For example, if the HTML for an element on the page looks like this: <div
class="some-class" id="some-id">...</div>, you can use the CSS selector
"div.some-class#some-id" to find this element.
7. XPath: This locator uses an XPath expression to locate an element. XPath is a
language for navigating and selecting elements in an XML document (including
HTML documents). It allows you to specify complex, hierarchical patterns for
locating elements on a page. For example, if you want to find all the <p> elements that
are descendants of the <div> element with the ID "some-id", you could use the XPath
expression "//div[@id='some-id']/p" to find these elements.
These are the main types of locators that are used in Selenium. Which one you use will
depend on the specific elements you are trying to locate on the page, and the HTML
structure of the page itself.
Tag
Attribute = Value
data-qa="hocewoqisi"
type="email"
class="text-input W(100%)"
name="username"
id="login-username"
# Preference
# id -> name -> className -> Link Text / Partial Text(a) -> CSS Selector -> XPath.
# XPath - 60%
# CSS Selector - 30%
# ID, Name, CLASS - 10%
findElement vs findElements
findElement() is a method used to locate a single element on a web page. It takes a locator as
an argument, and returns the first matching element that it finds. For example:
usernameField = driver.findElement(By.ID,"username"));
In this example, findElement() is used to locate the element with the ID "username". If it is
findElements() is similar to findElement(), but it returns a list of all matching elements instead of
allLinks = driver.findElements(By.TAGNAME("a"));
In this example, findElements() is used to locate all <a> elements on the page. These elements
It's important to note that if findElement() is used and no matching element is found, it will
A HTML form is a section of a web page that contains form elements, such as text fields,
checkboxes, and buttons. Forms allow users to enter data and interact with a website.
Forms are created using the <form> HTML tag. This tag defines the start and end of a form,
and it can have several attributes that determine how the form behaves.
For example, the action attribute specifies the URL of the server-side script that will process
the form data, and the method attribute specifies whether the form data will be sent to the
server using the GET or POST method.
When the user enters their username and password and clicks the "Log In" button, the form
data will be sent to the server-side script at the URL specified in the action attribute
(http://www.example.com/form-handler.php) using the POST method.
The server-side script can then process the form data and perform the desired action, such
as checking the user's credentials against a database and logging them in.
text Method
the getText() method is used to retrieve the text of an element on a web page. This method
can be called on an element, and it will return the text of the element, including any child
elements.
getAttribute() Method
the getAttribute() method is used to retrieve the value of an attribute of an element on a web
page.
element = driver.findElement(By.ID,"some-id");
element.getAttribute("class");
sendKeys
the sendKeys() method is used to enter text into a text field or text area on a web page
click()
the click() method is used to simulate a user clicking on an element on a web page
https://selectorshub.com/
[Assignment] - Invalid error message Capture for the Login Page of VWO.com
8. Fetch the locators - https://app.vwo.com/
9. Create a Python project and add pytest, alloure.
10.Add the Allure Report (Allure pytest)
11.Automate the two Test cases of VWO.com
a. Invalid Username and Valid Password.
12.Capture the error and pass the test.
13.Run them and share results.
The click() method is called on this element, which simulates the user clicking on the link
with their mouse. This will navigate the user to the URL specified in the href attribute of the
<a> element.
🛣️ Mastering XPath
What is XPath?
XPath is a query language for selecting nodes from an HTML / XML document.
XPath was defined by the World Wide Web Consortium.
//input[@data-qa="hocewoqisi"]
//input[@id="login-username"]
//input[@name="username"]
//li[@data-qa="rubehixixu"]/input
//*[@name="username"] - Slow way ( * wild card) - search for all the tags with unique name
= usernmae
For Button
TAG - h1, p, input, a, form, img, video, audio,button, table, ul, li, tr, div, select, span, -> Html
Tags
- Relative XPath
- Absolute XPath
- XPath Functions
Absolute XPath
- From the root
- Big problem - of on future any changes in html page
- Abs Xpath will break
-
/html/body/div[2]/div[1]/div[2]/div/div[1]/div/div/div[3]/form[1]/ul/li[1]/div/input
//input[@id='login-password']/../
Absolute XPath
1. Complete path from the Root Element.
2. If any element is added or deleted, Xpath fails.
3. /html/body/div[2]/div[1]/div[2]/div/div[1]/div/div/div[3]/form[1]/ul/li[1]/div/input
Relative Xpath
1. Short and simple to use.
2. You can simply start by referencing the element you want and go from there
Based on searching an element in DOM.//*[@id="login-username"].
//input[@id="login-username"]
XPath Functions
Contains()
//tag_name[contains(@attribute,'value_of_attribute')]
Starts-with()
//tag_name[starts-with(@attribute,'Part_of_Attribute_value')]
Text()
//tag_name[text()='Text of the element']
String functions
concat(string, ...): XPath concat function concatenated number of arguments and return to a
concatenated string.
starts-with(string, string): XPath start-with function return True/False. Return True if second
argument string is start with first argument.
contains(string, string) - XPath contains function return True/False. Return True if second
argument string is a contain of first argument.
string-length(string): XPath string-length function return the length of string.
substring-after(string, string): XPath substring-after function return the substring of the first
argument string base on first occurrence of the second argument string after all character.
https://katalon-demo-cura.herokuapp.com/
Operators - AND & OR
And Example
//tag_name[@name = 'Name value' and @id = ‘ID value’]
https://katalon-demo-cura.herokuapp.com/
OR Example
//input[@placeholder ='Full Name' or @type = 'text']
XPath Axes
In the XML documents, we have relationships between various nodes to locate those nodes
in the DOM structure.
● Ancestor
● Child, parent
● Descendant
● Following, following-sibling
● Self.
https://www.softwaretestinghelp.com/xpath-axes-tutorial/
//span[text()='Invalid Email']/ancestor::div
//*[@id="main-page"]/div[1]/child::div
//*[@id="js-main-container-wrap"]/child::div
//*[@id="js-main-container-wrap"]/following::div
https://devhints.io/xpath
● To select all elements with the tag "p" (paragraph), you could use the following
selector: p
● To select an element with the ID "main-heading", you could use the following
selector: #main-heading
● To select all elements with the class "error", you could use the following selector:
.error
● To select all elements with the attribute "disabled", you could use the following
selector: [disabled]
● To select all "a" elements that are descendants of a "nav" element, you could use the
following selector: nav a
form#login-form input[type="radio"]
CSS [attribute*=value] Selector
The [attribute*=”str”] selector is used to select those elements whose attribute value contains
the specified substring str.
CSS :first-child Selector The :first-child selector is used to select those elements which
are the first-child elements.
CSS :last-child Selector The :last-child Selector is used to target the last child element
of it’s parent for styling.
CSS :nth-child() Selector The :nth-child() CSS pseudo-class selector is used to match
the elements based on their position in a group of siblings.
CSS :nth-of-type() SelectorThe :nth-of-type() in css Selector is used to style only those
elements which are the nth number of child of its parent element.
⌛
Selenium Waits
Why Do We Need Waits In Selenium?
- Web applications are developed using Ajax and Javascript.
- New JS frameworks are more advanced and use AJax, react, and angular.
- elements which we want to interact with may load at different time intervals.
Implicit Wait
● Selenium Web Driver has borrowed the idea of implicit waits from Watir.
● If the element is not located on the web page within that time frame, it will throw an
exception.
● WebDriver polls the DOM for a certain duration when trying to find any element.
● Global settings applicable to all elements
● It tells the web driver to wait for the x time before moving to the next command.
● Gives No Such Element Exception.
● Once it is set it is applicable to full automation script.
● Implicit wait is maximum time between the two commands.
● Different from time.sleep - time.sleep() - It will sleep time for script/ Py Int.
● Not good way to use it in script as it's sleep without condition.
● Do not mix implicit and explicit waits. Doing so can cause unpredictable wait times.
driver = webdriver.Chrome()
driver.implicitly_wait(10) # Wait up to 10 seconds for elements to
appear
driver.get("https://example.com")
Explicit Wait
Explicit Wait in Selenium is used to tell the Web Driver to wait for certain conditions
(Expected Conditions) or maximum time exceeded before throwing
“ElementNotVisibleException” exception
driver = webdriver.Chrome()
driver.get("https://example.com")
The following are the Expected Conditions that can be used in Selenium Explicit Wait
You can use various expected conditions with explicit waits, such as:
[Assignment] Fix the VWO login page with the heading page visibility, Use Expected
Condition
Fluent Wait
Fluent Wait instance defines the maximum amount of time to wait for a condition as well as
the frequency with which to check the condition
- Exception - NoSuchElementException
- Waiting 30 seconds for an element to be present on the page, checking for its
presence once every 5 seconds.
driver = webdriver.Chrome()
driver.get("https://example.com")
https://www.selenium.dev/
documentation/en/webdriver/
waits/
Ref - https://www.guru99.com/implicit-explicit-waits-selenium.html
Implicit Wait Explicit Wait
● Implicit Wait time is applied to all the ● Explicit Wait time is applied only to those element
elements in the script by us
● In Implicit Wait, we need not specify ● In Explicit Wait, we need to specify “ExpectedCon
“ExpectedConditions” on the element to be located
element to be located
● It is recommended to use when the ● It is recommended to use when the elements are
elements are located with the time load and also for verifying the property of the elem
frame specified in Selenium implicit like(visibilityOfElementLocated,
wait elementToBeClickable,elementToBeSelected)
https://the-internet.herokuapp.com/dropdown
Handling Dynamic Dropdowns
1. We will use the XPath axes.
2. We will use the advanced css selectors for the same.
3. Traditional select classes won't work.
Alert in Selenium
An alert is a small window that appears on top of a web page and displays a message to the
user. Most of the time, alerts are used to show important information or ask the user for
something.
https://the-internet.herokuapp.com/javascript_alerts
Prompt Alert
Confirmation Alert
Handle Alert in Selenium WebDriver
# Now you can interact with the alert using the driver.switch_to.alert
method
alert = driver.switch_to.alert
# After interacting with the alert, you can continue with the rest of
your test script
# ...
"<table>" - It defines a table. You can also say that it's the starting point of a table.
<thead>
<tbody>
"<th>" - It defines a header cell, which means you should define your headings inside th tag.
"<tr>" - It defines a row in a table.
"<td>" - It defines a cell in a table. "td" always lie inside the tr tag.
//table[@id="customers"]
//table[contains(@id,"cust")]
Example -
https://awesomeqa.com/webtable.html
Static Table - Data will not change.
Actions, Windows and iframe.
Actions class is an ability provided by Selenium for handling keyboard and mouse events.
● Keyboard Events
● Mouse Events
● Wheel Mouse
import pytest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import
ActionChains
from selenium.webdriver.common.by import By
@pytest.mark.actions
def test_01_actions():
# Initialize the Firefox driver
driver = webdriver.Firefox()
link = driver.find_element(By.XPATH,
"//a[contains(text(), 'Click here to Download File')]")
actions.context_click(link).perform()
Keyboard Events
ActionChains(driver)\
.key_down(Keys.SHIFT)\
.send_keys("abc")\
.perform()
KeyUp(KeyCode) - Performs a key release. It has to be used after keyDown to release the
key.
ActionChains(driver)\
.key_down(Keys.SHIFT)\
.send_keys("a")\
.key_up(Keys.SHIFT)\
.send_keys("b")\
.perform()
Send Keys
ActionChains(driver)\
.send_keys("abc")\
.perform()
Send to Element
Mouse actions
● Click and hold
● Click and release
● Context Click
● Back Click
● Double click
● Move to element
● Move by offset
● Scroll to element
● Scroll by given amount
● Scroll from an element by a given amount
● Scroll from an element with an offset
File Upload
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
upload_file = driver.find_element(By.XPATH,
"//input[@id='fileToUpload']")
upload_file.send_keys("/Users/pramod/Documents/Course/apitesting.jpeg")
driver.find_element(By.NAME, "submit").click()
# Quit the driver
driver.quit()
Window:
In any browser, a window is the main webpage to which the user is directed after clicking on
a link or URL. Such a window in Selenium is referred to as the "parent window also known
as the main window which opens when the Selenium WebDriver session is created and has
all the focus of the WebDriver.
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
@pytest.mark.usefixtures("driver")
def test_01_windows(driver):
# Open the page
driver.get("https://the-internet.herokuapp.com/windows")
# Store the handle of the current window
main_window_handle = driver.current_window_handle
# Find the "Click Here" link
link = driver.find_element(By.LINK_TEXT, "Click Here")
# Click the link to open a new window
link.click()
# Store the handles of all open windows in a list
window_handles = driver.window_handles
# Iterate through the list of window handles
for handle in window_handles:
# Switch the focus to each window in turn
driver.switch_to.window(handle)
# Check if the text "New Window" is present in the window
if "New Window" in driver.page_source:
print("The text 'New Window' was found in the new window.")
break
# Switch the focus back to the main window
driver.switch_to.window(main_window_handle)
if __name__ == "__main__":
pytest.main([__file__])
IFRAME
An iframe (short for inline frame) is an HTML element that allows you to embed another
HTML document within the current document. Iframes are often used to embed videos,
advertisements, or other external content on a webpage.
1.
2. By Index
3. By Name or Id
4. By Web Element
Solution
i
import time
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
@pytest.fixture
def driver():
driver = webdriver.Chrome()
yield driver
# Close the web driver
driver.quit()
@pytest.mark.usefixtures("driver")
def test_02_windows_actions_complex(driver):
URL =
"https://app.vwo.com/#/analyze/osa/13/heatmaps/1?token=eyJhY2NvdW50X2lkI
jo2NjY0MDAsImV4cGVyaW1lbnRfaWQiOjEzLCJjcmVhdGVkX29uIjoxNjcxMjA1MDUwLCJ0e
XBlIjoiY2FtcGFpZ24iLCJ2ZXJzaW9uIjoxLCJoYXNoIjoiY2IwNzBiYTc5MDM1MDI2N2QxN
TM5MTBhZDE1MGU1YTUiLCJzY29wZSI6IiIsImZybiI6ZmFsc2V9&isHttpsOnly=1"
driver.get(URL)
driver.maximize_window()
mainWindowHandle = driver.current_window_handle
ac = ActionChains(driver)
ac.move_to_element(driver.find_element(By.CSS_SELECTOR,
"[data-qa='yedexafobi']")).click().perform()
time.sleep(20)
window_handles = driver.window_handles
# Here we will check if child window has other child windows and
will fetch the heading of the child window
for handle in window_handles:
if mainWindowHandle != handle:
driver.switch_to.window(handle)
driver.switch_to.frame("heatmap-iframe")
driver.find_element(By.CSS_SELECTOR,
"[data-qa='liqokuxuba']").click()
if __name__ == "__main__":
pytest.main([__file__])
JavaScript executor -
The JavaScript Executor is a feature of the Selenium WebDriver that allows you to execute
JavaScript code within the context of the current page.
This can be useful for interacting with elements on the page that are not directly accessible
through the Selenium API, or for bypassing certain limitations of the Selenium API.
Here are some common functions that you can use with the JavaScript Executor in
Selenium:
Dynamic Elements
let’s say ‘id’ of a username field is ‘uid_123’
Class=”abc-kkj3k2jk3j2”
id=”web-2323sdsdsd”
Use any of the Techq.
● [contains(@id,’uid’)]”
● /*[starts-with(@id,’uid’)]
● Relative Locators
● Xpath Axes
● Custom CSS Selectors
Project CRM
Selenium Exception
NoSuchElementException: This exception is thrown when the web driver is unable to
locate an element on the page using the specified search criteria.
NoSuchFrameException: This exception is thrown when the web driver is unable to switch
to a specified frame.
NoAlertPresentException: This exception is thrown when the web driver is unable to find
an alert box on the page.
TimeoutException: This exception is thrown when the web driver times out while waiting for
an element to be located or an action to be performed.
WebDriverException: This is a general exception that is thrown when an error occurs while
interacting with the web driver.
- Waits
- Try and Except
1. What is SVG - Scalable Vector Graphics to define graphics for web.
a. XML based language to create 2-D graphics/images with animation and
interactivity.
b. Uses geometrical figures to draw an image.
https://www.w3schools.com/graphics/tryit.asp?filename=trysvg_myfirst
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
@pytest.fixture
def driver():
driver = webdriver.Chrome()
yield driver
driver.quit()
def test_svg_demo(driver):
driver.get("https://flipkart.com")
driver.maximize_window()
search_input = driver.find_element(By.NAME, "q")
search_input.send_keys("AC")
search_element = driver.find_element(By.XPATH,
"//*[local-name()='svg']/*[local-name()='g' and @fill-rule='evenodd']")
actions = ActionChains(driver)
actions.move_to_element(search_element).click().perform()
driver.get("https://www.amcharts.com/svg-maps/?map=india")
states_list = driver.find_elements(By.XPATH,
"//*[name()='svg']/*[name()='g'][7]/*[name()='g']/*[name()='g']/*[name(
)='path']")
for state in states_list:
aria_label = state.get_attribute("aria-label")
print(aria_label)
if aria_label == "Tripura ":
actions.move_to_element(state).click().perform()
break
if __name__ == "__main__":
pytest.main(["-v"])
Shadow DOM
● Shadow DOM is a web standard that provides encapsulation for DOM and CSS in a
web component.
● Elements inside a Shadow DOM are hidden from the main document's DOM, and the
styles defined within a Shadow DOM do not affect the main document's styles, and
vice versa.
<!DOCTYPE html>
<html>
<head>
<title>Shadow DOM Example</title>
</head>
<body>
<my-custom-element>
#shadow-root
<p>This is content inside Shadow DOM</p>
</my-custom-element>
</body>
</html>
ScreenShot
● Simple Selenium Method to take screenshot
Relative Locators in Selenium
https://www.selenium.dev/documentation/webdriver/elements/locators/
@pytest.fixture
def setup_teardown():
driver = webdriver.Chrome()
driver.get("https://app.vwo.com") # Replace with your website
URL
driver.maximize_window()
yield driver
driver.quit()
https://www.selenium.dev/documentation/test_practices/encouraged/page_object_models/
What is the Main difference between Page Object Model and Page Factory in Seleniu…
Selenium Manager (Beta)
● Selenium Manager is a binary generated with Rust that manages driver installation.
● Start the grid with this additional argument: --selenium-manager true
● https://www.selenium.dev/documentation/selenium_manager/
Selenium Grid
● Want to run tests in parallel across multiple machines? Then, Grid is for you.
● Selenium Grid allows the execution of WebDriver scripts on remote machines by
routing commands sent by the client to remote browser instances.
Selenium Framework
Parallel Test
Reference
1. https://www.geeksforgeeks.org/css-selectors-complete-reference/?ref=lbp
2. https://google.com
3.
On Windows
set path="C:\Users\sikhi\AppData\Local\Programs\Python\Python312"
set path="C:\Users\sikhi\AppData\Local\Programs\Python\Python312\Scripts"
pip install -r requirements.txt
pytest tests\integration_test\test_crud.py
On Mac
cd "/Users/pramod/.jenkins/workspace/Python 1x Automation"
pip3 install -r requirements.txt
/Library/Frameworks/Python.framework/Versions/3.9/bin/pytest
tests/integration_test/test_crud.py -s -v --html=report.html --alluredir=./reports
/opt/homebrew/bin/python3 -m venv .
source ./bin/activate
pip install allure-pytest selenium pytest selenium-page-factory pytest-html openpyxl
pyyaml faker openpyxl pytest-xdist python-dotenv
pytest tests/test/vwoLoginTests/test_vwo_login_pf.py
deactivate
java -version
It should look something like this
Just copy these commands and paste them onto your terminal.
readlink -f $(which java)