Selenium with Python | How to write code of selenium web driver using Python Porgramming Language

0

Selenium with Python | How to write code of selenium web driver using Python Porgramming Language 

What is selenium?

It is automation based software system that is used to implement functional testing and regression testing operation for web application.

selenium provide various component to pefrom testing operation using varius programming language.

now the selenium 4 is the latest version of selenium.

Selenium Component

1) Selenium IDE

1) Web Driver

3) Selenium GRID

4) Selenium Framework (Data driven, keyword driven, hybrid driven)

python filename.py


How to create selenium environment under windows for python programming language

1) install python (enable pip and configure python path)

2) open cmd and write  pip install selenium

3) create folder under any drive and open this folder using VS Code

4) create python file and write this script


from selenium import webdriver

driver = webdriver.Chrome()

driver.get("https://www.google.com/")

driver.quit()

5) open VS Code terminal and execute this script.

python filename

(note selenium 4, no need to download and install chrome driver.)



Create Selenium Web Script to open site with 5 seconds

from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get("https://www.google.com/")
time.sleep(5)
driver.quit()

..........................................................
Locator in selenium:-

It is used to locate the element of form using various html attribute?


<input type="text" name="txt1" id="txt2" class="cls" /> <input type="text" /> selenium 3 find_element_by_name("txt1") find_element_by_id("txt2") find_element_by_classname("cls") find_element_by_xpath("//html/body/input[1]") selenium 4 find_element("name","element-name") find_element("id","element-name") find_element("class","class-name") find_element("xpath","xpath")
What is Command in Selenium:-

It is used to perform action under html form element,
if we want to write any content under form element or click on button
,radio,checkbox or other dynamic operation then we use set of command.

1) send_keys():- it is used to set the sequence of character under
textfield and textarea.


2) submit():- it is used to click the button.

Create an automation script to fill contact us form of eroomrent:-

from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get("https://eroomrent.in/contact.php")
driver.maximize_window()
driver.find_element("name","firstname").send_keys("jay kumar")
time.sleep(2)
driver.find_element("name","city").send_keys("jaykumar@gmail.com")
time.sleep(2)
driver.find_element("name","cnct").send_keys("9812312345")
time.sleep(2)
driver.find_element("name","subject").send_keys("welcome in g hdgfdg f")
time.sleep(2)
driver.find_element("name","btnsubmit").submit()
time.sleep(5)
driver.quit()

Create an automation script to search python.org website
search textfield?

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
driver = webdriver.Chrome()
driver.get("https://www.python.org/")
driver.maximize_window()
ele1=driver.find_element("name","q")
ele1.send_keys("loop")
ele1.send_keys(Keys.RETURN)
time.sleep(5)
driver.quit()

Create Automation Script to implement Login form:-

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
driver = webdriver.Chrome()
driver.get("https://eroomrent.in/ownerlogin.php")
driver.maximize_window()
driver.find_element("name","txtEmail").send_keys("shiva@yopmail.com")
time.sleep(2)
driver.find_element("name","txtPassword").send_keys("Shiva@123")
time.sleep(2)
driver.find_element("name","btnsubmit").click()
time.sleep(2)
driver.quit()

Create Automation Script to search module:-

from selenium import webdriver
import time
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get("https://eroomrent.in/index.php")
driver.maximize_window()
dropdown = Select(driver.find_element("name","ddlcat"))
# Select by visible text
dropdown.select_by_visible_text("Flat")
time.sleep(5)
dropdown = Select(driver.find_element("id","subcat"))
# Select by visible text
dropdown.select_by_index(2)
time.sleep(3)
dropdown = Select(driver.find_element("id","location"))
# Select by visible text
dropdown.select_by_index(2)
time.sleep(3)
element = driver.find_element(By.CLASS_NAME, "btn-one")
element.click()
time.sleep(3)
driver.quit()

click to linktext:-

from selenium import webdriver
import time
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get("https://eroomrent.in")
driver.maximize_window()
link = driver.find_element(By.LINK_TEXT,"FAQ")
# Click on the link
link.click()
time.sleep(5)
# Close the browser window
driver.quit()

Create Login Script to ShivaConceptDigital.com site

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get("https://shivaconceptdigital.com/")
driver.maximize_window()
driver.find_element(By.CLASS_NAME,"login-button").click()
time.sleep(2)
data=driver.find_element(
By.XPATH,"//html/body/main/div[3]/div/div/div/form/div[1]/div/input")
data.send_keys("testing@yopmail.com")
time.sleep(2)
driver.find_element(
By.XPATH,"//html/body/main/div[3]/div/div/div/form/div[2]/div/input").
send_keys("Test@123")
time.sleep(2)
driver.find_element(By.XPATH,"//*[@id='login-share']/form/div[4]/div/button").click()
time.sleep(2)
driver.quit()


What is Locator and Type of Locator in Selenium:-

Selenium is used to locate the element using various HTML attribute.

1)  by name

2)  by id

3)  By Classname

4)  By LinkText

5)  By partialLinkText

6)  By Css Selector

    1)  By classname    ".classname"
    2)  By Tagname and Classname  "tagname.classname"
    3)  By Tagname and Attributename "tagname[attribute=value]
    4)  By Tagname, Classname and Attributename
       "tagname.clsssname[attribute=value]"

    5)  By Tagname and ID
         "tagname.id"

element.send_keys("d://img.jpg")

Basic Example of Selenium CSS Selector Locator:-

from selenium import webdriver
import time
driver = webdriver.Chrome()
from selenium.webdriver.common.by import By
driver.get('https://www.shivaconceptsolution.com/backupmain/test.html')
element = driver.find_element(By.CSS_SELECTOR,"input[id=txt1]") # tag and id
element.send_keys('welcome in c#')
element1 = driver.find_element(By.CSS_SELECTOR,"input[type=date]") # tag and attribute
element1.send_keys('10-10-2024')
element2 = driver.find_element(By.LINK_TEXT,"Click")
element2.click()
time.sleep(2)
driver.back()
time.sleep(5)
driver.quit()

Drag and drop example in selenium Web Driver:-

from selenium import webdriver
from selenium.webdriver import ActionChains
import time
driver = webdriver.Chrome()
driver.get('https://jqueryui.com/droppable/')
driver.switch_to.frame(0)
source1 = driver.find_element('id','draggable')
target1 = driver.find_element('id','droppable')
actions2 = ActionChains(driver)
actions2. drag_and_drop(source1, target1). perform()
time.sleep(5)

Move between Frame in Selenium Web Driver:-

from selenium import webdriver
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://the-internet.herokuapp.com")
#to refresh the browser
driver.refresh()
driver.find_element(By.LINK_TEXT,"Frames").click()
driver.find_element(By.LINK_TEXT,"Nested Frames").click()
# to switch to frame with frame name
driver.switch_to.frame("frame-bottom")
time.sleep(2)
s=driver.find_element(By.XPATH,"//html/body").get_attribute('innerText')
print(s)
driver.switch_to.default_content()
driver.quit()

Popbox handling in Javascript:-
....................................................
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://www.shivaconceptsolution.com/backupmain/test3.html")
driver.find_element(By.XPATH,"//html/body/input[1]").click()
data=driver.switch_to.alert.text
driver.switch_to.alert.accept()
print(data)
driver.quit()
..............................................................................
..........................................................

Set cookie on Selenium Web Driver;-

from selenium import webdriver
import time
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://www.shivaconceptsolution.com/backupmain/test3.html")
cookie = {'name' : 'foo', 'value' : 'bar'}
driver.add_cookie(cookie)
# And now output all the available cookies for the current URL
print(driver.get_cookies())


Popbox example in selenium:-

from selenium import webdriver
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.by import By
from selenium.webdriver.common.alert import Alert
driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://www.shivaconceptsolution.com/backupmain/test3.html")
driver.find_element(By.XPATH,"//html/body/input[3]").click()
wait = WebDriverWait(driver, 10)
wait.until(expected_conditions.alert_is_present())

# Store the alert in a variable for reuse
alert1 = Alert(driver)

# Type your message
alert1.send_keys("Selenium")

# Press the OK button
time.sleep(3)

print(driver.switch_to.alert.text)
print(alert1.text)
alert1.accept()
driver.quit()


from selenium import webdriver
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.maximize_window()
driver.get('https://www.selenium.dev/selenium/web/dynamic.html')
revealed = driver.find_element(By.ID, "revealed")
driver.find_element(By.ID, "reveal").click()
wait = WebDriverWait(driver, timeout=2)
wait.until(lambda d : revealed.is_displayed())
revealed.send_keys("Displayed")
assert revealed.get_property("value") == "Displayed"
time.sleep(5)


Fluentwait Example in selenium webdriver?

from selenium import webdriver
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.by import By
from selenium.common import NoSuchElementException, ElementNotInteractableException
driver = webdriver.Chrome()
driver.maximize_window()
driver.get('https://www.selenium.dev/selenium/web/dynamic.html')
revealed = driver.find_element(By.ID, "revealed")
driver.find_element(By.ID, "reveal").click()
errors = [NoSuchElementException, ElementNotInteractableException]
wait = WebDriverWait(driver, timeout=2, poll_frequency=.2, ignored_exceptions=errors)
wait.until(lambda d : revealed.send_keys("Displayed") or True)
assert revealed.get_property("value") == "Displayed"


find_elements example in selenium web driver:-

from selenium import webdriver
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.maximize_window()
driver.get('https://shivaconceptdigital.com/')
images = driver.find_elements(By.TAG_NAME, "img")
print(len(images))
for data in images:
    print(data.get_attribute("src"))

................................................................................

ActionChains in Selenium in Web Driver:-

In Selenium WebDriver with Python, ActionChains is a class that allows you to perform
complex user interactions like mouse movements, keyboard actions, and more.
It's particularly useful for handling scenarios that require more than simple clicks
or keystrokes.

ActionChain Mousemove example to open sub menu:-

from selenium import webdriver
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
driver = webdriver.Chrome()
driver.maximize_window()
driver.get('https://eroomrent.in/')
actions = ActionChains(driver)
element = driver.find_element(By.LINK_TEXT,"Owner-G")
actions.move_to_element(element).perform()
time.sleep(3)
driver.find_element(By.LINK_TEXT,"Login Here").click()
time.sleep(5)
driver.quit()


ACTION EXAMPLE 2 TO HANLDE KEYWORD ELEMENTS, IN THIS EXAMPLE I HAVE EXPLAINED
HOW TO COPY CONTENT FROM ONE TEXTFIELD TO ANOTHER TEXTFIELD.

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
import time
# Initialize WebDriver (for example, using Chrome)
driver = webdriver.Chrome()

try:
    # Open a webpage with two text fields
    driver.get("https://www.shivaconceptsolution.com/backupmain/test.html")

    # Locate the source and destination text fields by their IDs (you can use any locator method)
    source_field = driver.find_element("id","txt1")
    destination_field = driver.find_element("id","txt3")
    source_field.send_keys('welcome')
    # Clear destination field (optional, if you want to replace the content)
    destination_field.clear()

    # Click and select all text in the source field using ActionChains
    actions = ActionChains(driver)
    actions.move_to_element(source_field).click().key_down(Keys.CONTROL).send_keys("a").key_up(Keys.CONTROL)

    # Perform the 'copy' action (CTRL+C)
    actions.key_down(Keys.CONTROL).send_keys("c").key_up(Keys.CONTROL)

    # Click on the destination field and perform 'paste' action (CTRL+V)
    actions.move_to_element(destination_field).click().key_down(Keys.CONTROL).send_keys("v").key_up(Keys.CONTROL)

    # Execute the actions
    actions.perform()
    time.sleep(3)

except Exception as e:
    print(f"An error occurred: {e}")

finally:
    # Close the WebDriver
    driver.quit()


What is Pytest and how to install Pytest:-

Pytest is a selenium framework similar to TESTNG framework of Java language .
it provide parallel test case execution using predefine API methods.

it can be used for API testing even though we can use pytest to
write simple to complex test

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. how to install pytest pip install pytest cofirm pytest installation pytest -h Most important rules for pytest Running pytest without mentioning a filename will run all files of format
test_*.py or *_test.py in the current directory and subdirectories.
Pytest automatically identifies those files as test files.
We can make pytest run other filenames by explicitly mentioning them.
Pytest requires the test function names to start with test.
Function names which are not of format test* are not considered as test functions
by pytest. We cannot explicitly make pytest consider any function not starting with
test as a test function.


Example of Pytest for single file:-

create the filename test_square.py

import math

def test_sqrt():
   num = 25
   assert math.sqrt(num) == 5

def testsquare():
   num = 7
   assert 7*7 == 40

def testquality():
   assert 10 == 10

pytest -v

Example of Pytest for multiple files:-

create two separate file test_square.py and test_greater.py and execute them

test_square.py already created

test_greater.py

def test_greater():
   num = 100
   assert num > 100

def test_greater_equal():
   num = 100
   assert num >= 100

def test_less():
   num = 100
   assert num < 200

pytest -v (run all test files)
pytest test_compare.py -v (run particular test files)
.......................................................................

How to execute particular method in a complete test case using pytest?

To execute the tests containing a string in its name we can use the
following syntax −

pytest -k <substring> -v
-k <substring> represents the substring to search for in the test names.

Now, run the following command −

pytest -k great -v

Grouping the test into Pytest:-

It is used to create logical gorup of function under multiple files.
python provide marker to mark the test case method to create grouping.

Syntax to create the marker:-

@pytest.mark.<markername>

Syntax to execute marker method

pytest -m <markername> -v

Create two separate files under same directory:-

test_compare.py
import pytest
@pytest.mark.great
def test_greater():
   num = 100
   assert num > 100

@pytest.mark.great
def test_greater_equal():
   num = 100
   assert num >= 100

@pytest.mark.others
def test_less():
   num = 100
   assert num < 200

create file test_square.py

import pytest
import math
@pytest.mark.square
def test_sqrt():
   num = 25
   assert math.sqrt(num) == 5

@pytest.mark.square
def testsquare():
   num = 7
   assert 7*7 == 40

@pytest.mark.others
def test_equality():
   assert 10 == 11

What is fixtures?

It is special function type of pytest that will execute under each test case method.

it is used to reduce the common code of testcase methods such as database connection

, authentication etc.

Syntax to define fixtures:

@pytest.fixture

Example of this program

import pytest

@pytest.fixture
def input_value():
   input = 39
   return input

def test_divisible_by_3(input_value):
   assert input_value % 3 == 0

def test_divisible_by_6(input_value):
   assert input_value % 6 == 0

Common fixtures:-

We can create separate file for fixtures that can be automatically called into multiple

files.


Code to create common fixtures:

create conftest.py

import pytest

@pytest.fixture
def input_value():
   input = 39
   return input


create test_div_by_3_6.py

import pytest

def test_divisible_by_3(input_value):
   assert input_value % 3 == 0

def test_divisible_by_6(input_value):
   assert input_value % 6 == 0

create test_div_by_13.py

import pytest

def test_divisible_by_13(input_value):
   assert input_value % 13 == 0


execute
pytest -k divisible -v (substring exeuction)


Parameterizing testing:-

using this we can pass multiple input parameter with output parameter
and check result.


create separate folder under project and create file test_parameterexample

import pytest
@pytest.mark.parametrize("num, output",[(1,11),(2,22),(3,35),(4,44)])
def test_multiplication_11(num, output):
   assert 11*num == output

run this script

pytest -k multiplication -v

Xfail and skip :-

Xfail is used to execute the test case but ignore the detailed description but
skip marker will skip the execution of test case method.

import pytest
@pytest.mark.xfail
@pytest.mark.great
def test_greater():
   num = 100
   assert num > 100

@pytest.mark.xfail
@pytest.mark.great
def test_greater_equal():
   num = 100
   assert num >= 100

@pytest.mark.skip
@pytest.mark.others
def test_less():
   num = 100
   assert num < 200

pytest -k skipfail -v
What is Maxfail features in Pytest:-

It is used to break the test case execution of Number of failure of test case method.

it is most important case when we execute test case before release of software product
we need 100% accuracy.

import pytest
import math

def test_sqrt_failure():
   num = 25
   assert math.sqrt(num) == 6

def test_square_failure():
   num = 7
   assert 7*7 == 40

def test_equality_failure():
   assert 10 == 11

pytest test_example.py -v --maxfail 1

What is Parallel Text Execution:-

When Test suite is large and if we want to execute multiple process similtenious

with multiple workers then we can use it.
pip install pytest-xdist
pytest -n 3
3 workers are working simletenious under parallel test case execution.

How to create log file under xml format

pytest test_multiplication.py -v --junitxml="result.xml"

Data driven framework:-

data from external repository then we will use data driven framework
first install
pip install openpyxl
create excel file
import openpyxl
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
excel_path = 'd:\\testcase2.xlsx'
workbook = openpyxl.load_workbook(excel_path)
sheet = workbook.active
uname=''
upass=''
for row in sheet.iter_rows(min_row=0): # Assuming data starts from the second row
   
    username = row[0].value
    password = row[1].value
    if username!=None:
        uname=username
        upass=password
    else:
        break
   
       
print(uname,upass)
driver = webdriver.Chrome()
driver.get('https://eroomrent.in/ownerlogin.php')
driver.find_element(By.NAME, 'txtEmail').send_keys(uname)
driver.find_element(By.NAME, 'txtPassword').send_keys(upass)
driver.find_element(By.NAME, 'btnsubmit').click()
time.sleep(3)

Create Complete code of data driven framework to write and read 
import openpyxl
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
excel_path = 'd:\\testcase2.xlsx'
workbook = openpyxl.load_workbook(excel_path)
sheet = workbook.active
uname=[]
upass=[]
for row in sheet.iter_rows(min_row=0): # Assuming data starts from the second row
   
    username = row[0].value
    password = row[1].value
    if username!=None:
        uname.append(username)
        upass.append(password)
    else:
        break
   
       
print(uname,upass)
driver = webdriver.Chrome()
driver.get('https://eroomrent.in/ownerlogin.php')
ack=''
for i in range(1,len(uname)):
 
  driver.find_element(By.NAME, 'txtEmail').send_keys(uname[i])
  driver.find_element(By.NAME, 'txtPassword').send_keys(upass[i])
  driver.find_element(By.NAME, 'btnsubmit').click()
  time.sleep(3)
  if(driver.current_url=='https://eroomrent.in/owner/dashboard.php'):
    print('login success')
    ack='login sucees'
    driver.find_element(By.LINK_TEXT,'Logout').click()
  else:
    ack='login fail'
    print('login fail')
  sheet.cell(row=i+1, column=3, value=ack)
  workbook.save(excel_path )
  driver.get('https://eroomrent.in/ownerlogin.php')
  time.sleep(3)













Post a Comment

0Comments

POST Answer of Questions and ASK to Doubt

Post a Comment (0)