Python With Slenium
Python With Slenium
By
Sathish Kumar R
Selenium installation
Open the command prompt and type “Python -m pip install -
U Selenium “ press enter
Sample project with package and python file
creation
How to open the browser
• from selenium import webdriver
class locator:
driver =
webdriver.Chrome('D:\Software\chromedriver_win32\chromedriver.ex
e’)
To enter the url
driver.get("https://en-gb.facebook.com/")
How to maximize and close the browser
To Maximize the window (fit to the screen)
driver.maximize_window()
To Minimize the window
• driver.minimize_window();
To set in to particular size
• driver.set_window_size(300,600)
To close the browser
• driver.close()
To close the session
• self.driver.quit()
Locators Method Syntax Description
E.g :
/html/body/div[2]/div[1]/div/h4[1]/b/html[1]/body[1]/div[2]/div[1]/div[1]/h4[1]/b[1]
Relative Xpath
Relative Xpath starts from the middle of HTML DOM structure. It starts with double forward slash (//). It can search
elements anywhere on the webpage, means no need to write a long xpath and you can start from the middle of HTML
DOM structure. Relative Xpath is always preferred as it is not a complete path from the root element.
E.G :
//div[@class='featured-box cloumnsize1']//h4[1]//b[1]
Locators –Xpath :Relative Xpath
Using XPath Handling complex & Dynamic elements in Selenium
1) Basic Xpath
2) Contains()
3) Using OR & AND
4) Xpath Starts-with
5) XPath Text() Function
1. Basic Xpath
XPath expression select nodes or list of nodes on the basis of attributes like ID , Name, Classname, etc. from the
XML document as illustrated below.
Xpath=//Tagname[@Attribute=‘Value']
Locators –Xpath :Relative Xpath
2. Contains
Contains() is a method used in XPath expression. It is used when the value of any attribute changes dynamically
Xpath=//*[contains(@Attribute,’Value’)]
4. Xpath Starts-with
n this method, the starting text of the attribute is matched to find the element whose attribute value changes
dynamically. You can also find elements whose attribute value is static (not changes).
Locators –Xpath :Relative Xpath
Xpath=//Tagname[starts-with(@attribute,’value’)]
f) Parent:
Selects the parent of the current node as shown in the below screen.
Xpath=//*[@id='rt-feature']//parent::div
h) Descendant:
Selects the descendants of the current node as shown in the below screen.it identifies all
the element descendants to current element ( ‘Main body surround’ frame element) which
means down under the node (child node , grandchild node, etc.).
Xpath=//*[@id='rt-feature']//descendant::a
Syncronization
These days, most of the web apps are using AJAX techniques. When a
page is loaded by the browser, the elements within that page may load
at different time intervals. This makes locating elements difficult: if an
element is not yet present in the DOM, a locate function will raise an
ElementNotVisibleException exception. Using waits, we can solve this
issue. Waiting provides some slack between actions performed - mostly
locating an element or any other operation with the element.
EXPLICIT WAIT:
An explicit wait is a code you define to wait for a certain condition to
occur before proceeding further in the code
Syncronization – Explicit Wait
Syntax:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
• title_contains h_to_it
• presence_of_element_located • invisibility_of_element_located
.
• visibility_of_element_located • element_to_be_clickable
• visibility_of • staleness_of
• presence_of_all_elements_located • element_to_be_selected
• text_to_be_present_in_element • element_located_to_be_selected
• text_to_be_present_in_element_v • element_selection_state_to_be
alue • element_located_selection_state_t
o_be
• alert_is_present
Syncronization – time.sleep(sec)
Simply put, the time.sleep() takes as arguments the number of seconds
you want the program to halt or to be suspended before it moves
forward to the next step. Let's see this with the help of a simple
program, where we simply output the current time with a halt of 5
seconds in between the next execution - hence introducing a difference
of 5 seconds between each print of the current time.
selectByIndex()/
Drop-Down selects/deselects an option by its index
deselectByIndex()
Box
When you call methods for actions on the ActionChains object, the
actions are stored in a queue in the ActionChains object. When you call
perform(), the events are fired in the order they are queued up.
Mouse action - Methods
Method Description
Holds down the left mouse button on the source element, then moves to the
drag_and_drop
target element and releases the mouse button.
Holds down the left mouse button on the source element, then moves to the
drag_and_drop_by_offset
target offset and releases the mouse button.
Mouse action - Methods
move_by_offset Moving the mouse to an offset from current mouse position.
move_to_element_with_offs Move the mouse by an offset of the specified element, Offsets are
et relative to the top-left corner of the element.
reset_actions Clears actions that are already stored locally and on the remote end
Keyboard Actions - syntax
Action Arguments Description
keys_to_send – The keys to send.
Send keys to the element that is currently
send_keys(*keys_to_send) Modifier keys constants can be found in
in focus.
the Keys class.
alert_obj = driver.switch_to.alert
Handling Alert
• After the control has moved to Alert pop-up, we can do different
actions on it using the recommended methods as.
self.driver.find_element_by_xpath("//ul[@role='listbox']//li["+str(x)+"]").click()
break
WebTable Handle
def table(self,actualtext):
self.driver.get("http://www.leafground.com/pages/table.html")
totalrowvalue = self.driver.find_elements_by_xpath("//table[@id='table_id']//tr")
sizeofrowlist = len(totalrowvalue)
for x in range(2, sizeofrowlist+1):
totalcolumnvalue =
self.driver.find_elements_by_xpath("//table[@id='table_id']//tr[" + str(x) + "]//td")
sizeofcolumnlist = len(totalcolumnvalue)
text_Value = self.driver.find_element_by_xpath("//table[@id='table_id']//tr[" +
str(x) + "]//td[1]").text
print(text_Value)
if text_Value != actualtext:
self.driver.find_element_by_xpath("//table[@id='table_id']//tr[" + str(x) +
"]//td[3]//input").click()
#break
How to scroll the page
To perform scroll operation we can use the below methods
#scroll down
self.driver.execute_script("window.scrollTo(0, 600)",0) Pixel size
# scroll up
self.driver.execute_script("window.scrollTo(0, -600)", 0)
time.sleep(1)
# scroll right
self.driver.execute_script("window.scrollTo(600, 0)", 0)
time.sleep(1)
# scroll left
self.driver.execute_script("window.scrollTo(-600, 0)", 0)
How to scroll the page
# scroll bottom
self.driver.execute_script("window.scrollTo(0,
document.body.scrollHeight);")
element=self.driver.find_element_by_xpath("//h5[text()='Window']
//parent::a")
self.driver.execute_script("arguments[0].scrollIntoView();",
element)
Screenshot
Selenium offers a lot of features and one of the important and useful
feature is of taking a screenshot. In order to take a screenshot of
webpage save_screenshot() method is used. save_screenshot
method allows user to save the webpage as a png file.
driver.save_screenshot("image.png")
Argument :
filename or the full path you wish to save your screenshot to.
Action performed :
The screenshot will be saved in the same directory as the program, if
path is provided screenshot will be saved at that location only.
Handling Frames
We can handle frames in Selenium. A frame is an HTML element that
keeps a document within another document in a page. HTML has the
<frame> or <iframe> tags for embedding a frame inside a document.
There are multiple APIs available in Selenium to work with the frames.
They are listed below −
1. switch_to.frame(id)
2. switch_to.frame(name)
3. switch_to.frame(webelement)
4. switch_to.parent_frame()
5. switch_to.default_content()
Handling Frames
switch_to.frame(id)
This method is used to identify a frame with the help of frame id and then switch
the focus to that particular frame.
Syntax −
driver.switch_to.frame("frameid") - where frame id is the id attribute present
under the frame/iframe tag in HTML.
switch_to.frame(name)
This method is used to identify a frame with the help of frame name and then
switch the focus to that particular frame.
Syntax −
driver.switch_to.frame("framename") where frame name is the name attribute
present under the frame/iframe tag in HTML.
Handling Frames
switch_to.frame(webelement) :
This method is used to identify a frame with the help of frame webelement
and then switch the focus to that particular frame.
Syntax −
driver.switch_to.frame("frameclassname") where frameclassname is
the name of class attribute present under the frame/iframe tag in HTML.
switch_to.parent_frame()
This method is used to come out of the present frame, then we can access
the elements outside that frame and not inside of that frame.
switch_to.default_content()
This method is used to come out of all the frames and switch the focus at
the page. Once we move out, it loses the access to the elements inside the
frames in the page.
Handling Multiple Windows
We can handle child windows or tabs in Selenium. While working with
child windows, we need to always shift the browser focus to the child
windows, then perform operation on them.
By default, the focus remains on the first parent window. There are
multiple methods available in Selenium which are listed below −
current_window_handle
window_handles
switch_to.window(args)
This method fetches all the handle ids of the windows that are currently open.
Syntax −
driver.window_handles
w = driver.window_handles[2]
The above code gives the handle id of the second window opened in the present session.
switch_to.window(args)
This method switches the focus of Selenium to the window name mentioned in the arguments.
Syntax −
driver.switch_to.window(childwindow)
How to upload the file
1.Upload using send_keys for upload textbox
Syntax:
Webelement.send_Keys(“filepathof the file to be upload”)
How to upload the file
2.Upload through windows upload popup as below
self.driver.find_element_by_xpath("(//div[@class='input-file-
upload-hover-placeholder']//parent::div)[1]").click()
driver =
webdriver.Chrome('D:\Software\chromedriver_win32\chromedrive
r.exe')
driver.get("http://www.leafground.com/pages/download.html")
driver.maximize_window()
driver.find_element_by_link_text("Download Excel").click()
How to download the file – in specific folder
2 .Download the file in the specific folder
options = webdriver.ChromeOptions();
prefs = {"download.default_directory" :
"C:\\Users\\sathishkumar\\PycharmProjects\\SeleniumProject\\Downlo
adfile\\"}
options.add_experimental_option("prefs", prefs)
driver =
webdriver.Chrome('D:\Software\chromedriver_win32\chromedriv
er.exe',options=options)
self.driver.get("http://www.leafground.com/pages/download.html
")
self.driver.maximize_window()
self.driver.find_element_by_link_text("Download Excel").click()
Log Files
Log is used for logginf the information in to the file for tracking the
execution
Types of Logs
• Debug
• Info
• Warning
• Error
• Critical
logger= logging.getLogger()
Pytest – Testing Framework
Pytest is a python based testing framework, which is used to write and
execute test codes. In the present days of REST services, pytest is mainly
used for API testing even though we can use pytest to write simple to
complex tests, i.e., we can write codes to test API, database, UI, etc.
Advantages of Pytest
The advantages of Pytest are as follows −
• Pytest can run multiple tests in parallel, which reduces the execution time
of the test suite.
• Pytest has its own way to detect the test file and test functions
automatically, if not mentioned explicitly.
• Pytest allows us to skip a subset of the tests during execution.
• Pytest allows us to run a subset of the entire test suite.
• Pytest is free and open source.
• Because of its simple syntax, pytest is very easy to start with.
Pytest – Testing Framework
To Run the Pytest we can run by following way
Pytest provides two ways to run the subset of the test suite.
Fixtures :
Fixtures are functions, which will run before each test function to which it is applied. Fixtures are
used to feed some data to the tests such as database connections, URLs to test and some sort of
input data. Therefore, instead of running the same code for every test, we can attach fixture
function to the tests and it will run and return the data to the test before executing each test.
@pytest.fixture()
Pytest - Fixtures
• A test function can use a fixture by mentioning the fixture name as
an input parameter.
• This is basically used to execute few code before each test
• E.g
• import pytest
• @pytest.fixture
• def input_value():
• input = 39
• return input
• def test_divisible_by_3(input_value):
• assert input_value % 3 == 0
Pytest – Fixtures
• If we want to execute certain action post the test case then we
have use the following under yield in the fixtures
• @pytest.fixture
• def input_value():
input = 39
return input
Yield
Print(“I am post yield”)
Pytest – Fixtures (Conftest-file)
• We can define the fixture functions in this file to make them
accessible across multiple test files.
File name should be conftest.py
It should contains only fixtures so the each pytest file should not
have the fixtures
How to optimize the fixtures in testcase
Create a class underneath that create a test cases
Now provide the self as parameter to each test case
Then define the following syntax on above class
@pytest.mark.usefixtures(“fixturename”)
Pytest – Fixtures (Conftest-file)
How to run the fixture before the class but not each test cases then
Go to conftestfile and update as below
@pytest.fixture(scope=“class”)
@pytest.mark.usefixtures(“dataload”)
Class Test_classname
def test_testcase1(self,dataload):
print(dataload[0])
Class classname
def test_testcase1(self, crbrws):
print(crbrws)
Other way :
Multiple data set: (pick each test on each run)
Under the Fixtures
@pytest.fixture(params=[(“chrome”,”sathishkumar”,”password”),(”firefox”,”s
athish”,”kumar”),(”IE”,”thirdvalue”)])
def crbrws(paramvalue)
return paramvalue.param
Pytest – Fixtures (Conftest-file) -parameterization
Go to the class where your test cases contains and use the below
syntax just above the class
@pytest.mark.fixture(“crbrws”)
Class Test_classname
def test_testcase1(self , crbrws):
print(crbrws[1])
Reports
1.Html
Install pytest-html
To run
Pytest --html=reportname.html
2 : Html – Reporter
Install pytest-html-reporter
To run
Pytest –html-report=reportname.html