Program 6-Installation of Selenium: Setting up Selenium RC and
Selenium Web Driver.
Step 1:
• Install Python (if not already installed).
• Download from: https://www.python.org/downloads/.
• In the command prompt check the version which is installed using this command
python –version.
Step 2:
• Install Selenium WebDriver.
• To install Selenium WebDriver use this command : pip install selenium.
Step 3:
• https://googlechromelabs.github.io/chrome-for-testing/#stable click on this link and
open it in chrome browser.
• Search for the below given zip file and click on that to download.
Step 4:
• Now go to the File Explorer →Downloads→open the downloaded zip file. In that
open the zip file as it shows like this→ .In that copy the file named
as chromedriver.exe.
• In the next step go to C-Drive and create a new folder (Ex:tools).
• In that created new folder create one more folder named as chromedriver.
• Paste the file we have copied in the newly created folder as chromedriver.
• After this copy the path something look like this: (C:\tools\chromedriver).
• Now open “Edit the system environment variables” after opening this in bottom
we can see the button as “Environment Variables” .In both user variables and
syatem variables we can see the path section open and add the path copied in both
part.
• Then click on “OK” to add the path.
Step 5:
• Then go back to the command prompt verify that the chromedriver has installed
properly using the command as: chromedriver –version
Step 6:
• Open the Visual studio code.
• Create a new window and open new terminal.
• In terminal check whether Selenium and Chromedriver installed correctly or not.
• To check that type as chromedriver --version.
Step 7:
• Create a new folder in C-Drive and name it as “selenium”.
• Open selenium folder in VS-Code (Visual studio code).
• Create a new file name the file with .py extension (Ex:admin.py).
Type this code:
import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
service = Service("C:/tools/chromedriver/chromedriver.exe") # Change path if needed
driver = webdriver.Chrome(service=service)
driver.get("https://www.google.com")
print("Title:", driver.title)
time.sleep(10) # Keeps browser open for 10 seconds
driver.quit()
In terminal to run the code type as: python admin.py.
Output:
Step 8:
• Once again open command prompt.
• Type as: pip install selenium==2.53.1
• Now click on this link provided below:
https://selenium-release.storage.googleapis.com/index.html
• Then click on 2.53→ search for this selenium-server-standalone-2.53.1.jar.
• Open selenium folder that we have already created in C-Drive copy the jar file that
look something like this→ into the selenium folder .
Step 9:
• Go to VS-Code create an another file (Ex:index.py).
Type this code:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
import time
service = Service(executable_path="C:\\tools\\chromedriver\\chromedriver.exe") #
Update this path
options = Options()
driver = webdriver.Chrome(service=service, options=options)
driver.get("http://demoaut.katalon.com/")
time.sleep(2)
driver.find_element(By.XPATH, "//a[text()='Make Appointment']").click()
time.sleep(3)
driver.quit()
print(" Test Completed Successfully!")
Output: To run the code use this in terminal python index.py
Program 7 - Designing Testcases: Test Case design and Conversion
of Mapping and Templates using selenium tool and Manual test
cases mapping with Selenium test cases.
Step 1:
• Create a new file in a selenium folder, that was already in C-drive.
• Name the file (Ex: log.py).
Type this code:
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
# Initialize WebDriver
driver = webdriver.Chrome()
# Step 1: Open OrangeHRM Login Page
driver.get("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login")
time.sleep(3) # Wait for the page to load
# Step 2: Enter Username
driver.find_element(By.NAME, "username").send_keys("Admin")
# Step 3: Enter Password
driver.find_element(By.NAME, "password").send_keys("admin123")
# Step 4: Click Login Button
driver.find_element(By.XPATH, "//button[@type='submit']").click()
time.sleep(5)
# Step 5: Verify Login Success
if "dashboard" in driver.current_url:
print("Login Test Passed")
else:
print("Login Test Failed")
# Close browser
driver.quit()
Output: To run the code use this in terminal python log.py
Once the code is executed, the URL provided in the code opens directly in chrome and
automatically takes username and password , then you will be logged in.
In terminal you will see this:
Step 2:
• Create a another file in the same folder.
• Name the file (Ex: csvfile.py).
Type this code:
from openpyxl import Workbook
# Create a new Excel workbook and sheet
wb = Workbook()
ws = wb.active
ws.title = "TestData" # Rename the sheet
# Add headers
ws.append(["Username", "Password", "Expected Result"])
# Add test data
ws.append(["Admin", "admin123", "Pass"])
ws.append(["User1", "wrongpassword", "Fail"])
# Save the workbook
wb.save("testdata.xlsx")
print("Excel file 'testdata.xlsx' created successfully!")
Output: To run the code use this in terminal python csvfile.py
In terminal you will see this:
Step 3:
• Create a another file in the same folder.
• Name the file (Ex: final.py).
Type this code:
import pandas as pd
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
# Load test data from Excel
df = pd.read_excel("testdata.xlsx")
for index, row in df.iterrows():
print(f" Running test for Username: {row['Username']}")
# Initialize WebDriver
driver = webdriver.Chrome()
wait = WebDriverWait(driver, 10) # 10-second timeout
try:
# Open OrangeHRM login page
driver.get("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login")
# Wait for username and password fields and login button
username_field = wait.until(EC.presence_of_element_located((By.XPATH,
"//input[@name='username']")))
password_field = wait.until(EC.presence_of_element_located((By.XPATH,
"//input[@name='password']")))
login_button = wait.until(EC.element_to_be_clickable((By.XPATH,
"//button[@type='submit']")))
# Enter credentials and click login
username_field.send_keys(str(row["Username"]))
password_field.send_keys(str(row["Password"]))
login_button.click()
# Wait for URL to change indicating login attempt
wait.until(lambda d: d.current_url != "https://opensource-
demo.orangehrmlive.com/web/index.php/auth/login")
# Get current URL
current_url = driver.current_url
expected_result = row["Expected Result"].strip().lower() # Normalize string
# Check result based on expected outcome
if "dashboard" in current_url and expected_result == "pass":
print(f" Test Passed for {row['Username']}")
elif "dashboard" not in current_url and expected_result == "fail":
print(f" Test Passed for {row['Username']} (Expected Fail)")
else:
print(f" Test Failed for {row['Username']}")
except TimeoutException:
if row["Expected Result"].strip().lower() == "fail":
print(f" Test Passed for {row['Username']} (Timeout as expected)")
else:
print(f" Test Failed for {row['Username']} (Timeout)")
finally:
driver.quit()
Output: To run the code use this in terminal python finsl.py
You can see the below as a output.
After completing execution you will see the invalid credentials message in the website.
Program 8 - Using Selenium IDE: Develop a test suite containing
minimum 4 test cases.
Step 1:
• Open chrome browser , search for Selenium IDE for FireFox.
• Click on Download FireFox and get the extension button an FireFox installer.exe
will be downloaded.
• Click on FireFox installer.exe file. Now the extension will be downloaded.
Step 2:
• Open FireFox extensions.
Step 3:
• Open SeleniumIDE.
• Click on Create a new project.
• Name the project (Ex: lab8_info).
• Click on ok.
Step 4:
• https://the-internet.herokuapp.com/login
Type the above URL in the Playback base URL section.
• Click on Record Button.
• You can see the Tab as provided in the above image.
• 2-3 times in the username and password section proved wrong username and
password .
• Finally enter the correct details as given below:
Username : tomsmith
Password : SuperSecretePassword!.
Step 5:
• Once the recording is completed click on stop recording button then it displays to give
the Testcase name provide the name (Ex:testcase_1).
• Once testcase name is given click on “OK”.
Step 6:
• Click on run button.
• Once you run the testcase the website will be directly opened and logged In.
• Then in the IDE it will display as ‘testcase_1’completed successfully.
Program 9 - Test Suite: Conduct a test suite for any two web sites.
Step 1:
• Open SeleniumIDE.
• Click on Create a new project.
• Name the project (Ex: lab9_info).
• Click on ok.
Step 2:
• Now in the right side of the panel select “Test suites” .
• In the same panel we can see this “+” symbol click on that.
• After clicking it ask us to Add new suite then give name to the test suites
(Ex:lab9_test).
• Now click on add button.
Step 3:
• As we created a test suites in the same way select on “Tests” and click on
“+” .Give name to the test (Ex:test_case1).
• Then click on add button.
Step 4:
https://www.saucedemo.com/
Type the above URL in the Playback base URL section.
• Click on Record Button.
• You can see the website opening and type the Username and Password in the
requires section.
• Then press on “Login”.
• After logging In immediately click on “Logout”.
• This information will be recorded and saved in the Selenium IDE.
• Stop the recording.
Step 5:
• Create a new test case(Ex:test_case2).
Step 6:
• https://the-internet.herokuapp.com/login
Type the above URL in the Playback base URL section.
• Click on Record Button.
• You can see the website opening and type the Username and Password in the
requires section.
• Then press on “Login”.
• After logging In immediately click on “Logout”.
• Stop the recording.
Step 7:
• Now add the test cases to the already created test suite as lab9_test.
• Click on “Add tests” button.
• Check the both the test cases check box and click on “SELECT” button.
Step 8:
• Click on run all tests button
• Then you can see the testcases running.
After that will display as “completed successfully”.
Program 10 - Test Scripts: Develop and test a program to login a
specific web page using selenium test scripts.
Step 1:
• Open the VScode .
• Create a new file in a selenium folder, that was already in C-drive.
• Name the file (Ex: program_10.py).
Type the given code:
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
# Initialize WebDriver
driver = webdriver.Chrome()
# Step 1: Open OrangeHRM Login Page
driver.get("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login")
time.sleep(3) # Wait for the page to load
# Step 2: Enter Username
driver.find_element(By.NAME, "username").send_keys("Admin")
# Step 3: Enter Password
driver.find_element(By.NAME, "password").send_keys("admin123")
# Step 4: Click Login Button
driver.find_element(By.XPATH, "//button[@type='submit']").click()
time.sleep(5)
# Step 5: Verify Login Success
if "dashboard" in driver.current_url:
print("Login Test Passed")
else:
print("Login Test Failed")
# Close browser
driver.quit()
Output: To run the code use this in terminal python program_10.py
Once the code is executed, the URL provided in the code opens directly in chrome and
automatically takes username and password , then you will be logged in.
In terminal you will see this:
Program 11 - Test Scripts: Develop and test a program to provide
total number of objects present available on the page using
selenium test scripts.
Step 1:
• Open the VScode .
• Create a new file in a selenium folder, that was already in C-drive.
• Name the file (Ex: program_11.py).
Type the given code:
from selenium import webdriver
from selenium.webdriver.common.by import By
# Initialize WebDriver
driver = webdriver.Chrome()
# Open the Target Website
driver.get("https://demoqa.com/")
# Find all elements on the page
all_elements = driver.find_elements(By.XPATH, "//*")
# Count total number of elements
total_elements = len(all_elements)
# Print total count
print(f"Total number of objects (elements) on the page: {total_elements}")
# Print all objects' tag names and attributes
for index, element in enumerate(all_elements[:50], start=1): # Limiting to first 50 elements
try:
tag_name = element.tag_name
element_text = element.text.strip()
print(f"{index}. <{tag_name}> Text: {element_text if element_text else 'N/A'}")
except:
print(f"{index}. <Unknown Element>")
# Close browser
driver.quit()
Output: To run the code use this in terminal python program_11.py
• This website will be opened and searches for the tools which are in this site.
• In terminal you can see this output.
Program 12 - Practical Exercise and Wrap-Up: Build Test suit
with suitable application and complete end to end automation
process, Discussion on Best Practices and Q&A.
Step 1:
• Open the VScode .
• Create a new file in a selenium folder, that was already in C-drive.
• Name the file (Ex: program_12.py).
Type the given code:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
import time
def run_test():
# Setup
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)
driver.maximize_window()
try:
# Step 1: Navigate to site
driver.get("https://practicetestautomation.com/practice-test-login/")
# Step 2: Enter username and password
driver.find_element(By.ID, "username").send_keys("student")
driver.find_element(By.ID, "password").send_keys("Password123")
driver.find_element(By.ID, "submit").click()
# Step 3: Wait and validate
WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.TAG_NAME, "h1"))
header = driver.find_element(By.TAG_NAME, "h1").text
if "Logged In Successfully" in header:
print(" Test Passed: Successfully logged in!")
else:
print(" Test Failed: Login header mismatch")
except Exception as e:
print(f" Test Failed: {str(e)}")
driver.save_screenshot("error_screenshot.png")
finally:
time.sleep(2)
driver.quit()
# Run the test
if __name__ == "__main__":
run_test()
Output:
• The website will be automatically opened and logged In and logout.
• In terminal it display as: