Important Libraries

from selenium import webdriver 
from selenium.webdriver.chrome.service import Service 
from selenium.webdriver.support.ui import Select 
from selenium.webdriver.common.by lmport By 
from selenium.webdriver.support import expected_conditions as EC 
from selenium.webdriver.support.ui import WebDriverWait 
import time 
from selenium.webdriver.common.action_chains import ActionChains 
from selenium.webdriver.chrome.options import Options 
from selenium webdriver.remote.webelement import WebElement
  1. webdriver

imports the webdriver module from the Selenium library, which allows you to automate browser actions like clicking, typing and navigating.

  1. Service

Service is used to manage the lifecycle of the chromedriver.exe process (starting, stopping, and communication).

  1. Select

from selenium.webdriver.support.ui import Select imports the Select class, which is used to handle dropdown menus in Selenium.

  1. expected_conditions

from selenium.webdriver.support import expected_conditions as EC imports expected_conditions, which defines conditions to wait for (like element visibility) before performing actions.

  1. WebDriverWait

from selenium.webdriver.support.ui import WebDriverWait imports WebDriverWait, which is used to wait for a specific condition to be met before proceeding.

  1. ActionChains

from selenium.webdriver.common.action_chains import ActionChains imports ActionChains, which is used to perform complex user interactions like hover, drag-and-drop, and right-click.

  1. Options

from selenium.webdriver.chrome.options import Options imports Options, which is used to set Chrome-specific settings like headless mode, disabling extensions, etc.

  1. WebElement

Represents an HTML element.

Basic Code Examples

Google Search Example

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

# Path to chromedriver.exe
service = Service(r"Drivers\chromedriver.exe")
# Initialize WebDriver using Service
driver = webdriver.Chrome(service=service)
# Set page load timeout
driver.set_page_load_timeout(10)
# Open Google
driver.get("https://google.com")
# Find search input and send keys
driver.find_element(By.NAME, "q").send_keys("Hello Google")
time.sleep(5)
# Wait until the search button is clickable, then click
driver.find_element(By.NAME,"btnK").click()
# Wait for results to load
time.sleep(5)
# Close browser
driver.close()
driver.quit()
print("Test Completed")

Switch Windows Example

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
import time

from selenium.webdriver.common.by import By
service = Service(r"Drivers\chromedriver.exe")
driver = webdriver.Chrome(service=service)
driver.get("https://www.examples.com/")
time.sleep(2)
driver.maximize_window()
time.sleep(2)
time.sleep(2)
home_window = driver.current_window_handle
print(home_window)
time.sleep(2)
driver.switch_to.new_window('tab')
time.sleep(2)
driver.switch_to.window(home_window)
time.sleep(2)
ele = driver.find_elements(By.CLASS_NAME,"cat-img")
ele[0].click()
time.sleep(2)
time.sleep(2)
driver.close()

Things to know…

Headless Chrome

Headless mode is a configuration option in Selenium that enables running browser instances without displaying a visible UI.

Why?

This mode is particularly useful for automating tasks on cloud infrastructure, where a graphical interface is not available, or for running tests on a continuous integration/continuous deployment (CI/CD) pipeline.

Example
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

chromeOptions = Options()
chromeOptions.add_argument("--headless");
service = Service(r"E:\Jobs\TCS\Testing\Selenium\Drivers\chromedriver.exe");
driver = webdriver.Chrome(service=service,options=chromeOptions);
driver.get("https://google.com");
print(driver.title)
searchBox = driver.find_element(By.NAME,'q')
searchBox.send_keys("What is Selenuium?");
time.sleep(3)
driver.find_element(By.NAME,"btnK").click();
time.sleep(3)
print(driver.title)
driver.close();
driver.quit();
print("Completed");

📎 List of Chrome Driver Arguments: View the Resource


Topic-Wise-Examples

Switch to new browser instance of ‘window’ || ’tab’

driver.switch_to.new_window()

import time
from selenium import webdriver
from selenium.webdriver.chrome.service  import Service
from selenium.webdriver.common.by import By

service = Service(r"E:\Jobs\TCS\Testing\Selenium\Drivers\chromedriver.exe")
driver = webdriver.Chrome(service=service)
driver.get("https://search.brave.com/")
time.sleep(2)
googleSearchBox = driver.find_element(By.ID,"searchbox");
googleSearchBox.send_keys("What is NVIDIA Omniverse?");
time.sleep(2)
searchBtn = driver.find_element(By.ID,"submit-button");
searchBtn.click()
time.sleep(3)
print(driver.title)
driver.switch_to.new_window("tab");
driver.get("https://www.blender.org/")
print(driver.title)
time.sleep(5)
driver.close();
driver.quit();

To Select a Radio Button && Print a Text in Console

import time

from selenium import webdriver

from selenium.webdriver.chrome.service import Service

from selenium.webdriver.common.by import By

  

service = Service(r"E:\Jobs\TCS\Testing\Selenium\Drivers\chromedriver.exe")

driver = webdriver.Chrome(service=service)

driver.get("https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_input_type_radio")

time.sleep(2)

print(driver.title)

driver.switch_to.frame("iframeResult")

radioBtn = driver.find_element(By.ID,"html");

radioBtn.click()

textArea = driver.find_elements(By.TAG_NAME,"p")[0ii].text

print(textArea)

time.sleep(2)

driver.quit()

Select Dropdown Value and Print Text

import time

from selenium import webdriver

from selenium.webdriver.chrome.service import Service

from selenium.webdriver.common.by import By

from selenium.webdriver.support.ui import Select

  

service = Service(r"E:\Jobs\TCS\Testing\Selenium\Drivers\chromedriver.exe")

driver = webdriver.Chrome(service = service)

driver.get("https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_select")

time.sleep(2)

driver.switch_to.frame("iframeResult")

time.sleep(1)

dropdown = driver.find_element(By.ID,"cars");

time.sleep(2)

dropdowned = Select(dropdown);

time.sleep(2)

dropdowned.select_by_value("audi")

selected_text = dropdowned.first_selected_option.text

print(selected_text)

time.sleep(2)

driver.quit()

Handle Alert Window

*The Following code will click on alert btn then send keys to alert.

import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

service = Service(r"E:\Jobs\TCS\Testing\Selenium\Drivers\chromedriver.exe")
driver = webdriver.Chrome(service=service)
driver.get("https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_prompt")
time.sleep(2)
driver.switch_to.frame("iframeResult")
time.sleep(2)
driver.find_element(By.XPATH,"/html/body/button").click()
time.sleep(1)
alert1 = driver.switch_to.alert
time.sleep(1)
alert1.send_keys("Someone give me Chole Bhature and Kurkure Momos😭😭😭😭😭plzzz");
time.sleep(5)
alert1.accept()
time.sleep(5)
driver.close()
driver.quit()

Expected Conditions (EC)

Expected Conditions (EC) are used with WebDriverWait to handle dynamic web elements and ensure synchronization between the script and the browser.

Without EC, Selenium might try to interact with elements before they exist, causing NoSuchElementException or StaleElementReferenceException.

  1. Alert Html Script
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Random Alert Box</title>
    <script>
        function showAlert() {
            let randomDelay = Math.floor(Math.random() * 5000) + 1000; // Random delay between 1s to 5s
            setTimeout(() => {
                alert("This is a random alert!");
            }, randomDelay);
        }
    </script>
</head>
<body onload="showAlert()">
    <h2>Random Alert Box Example</h2>
    <p>Wait for the alert to appear randomly between 1 to 5 seconds.</p>
</body>
</html>
  1. Selenium Code to handle EC
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

service = Service(r"E:\Jobs\TCS\Testing\Selenium\Drivers\chromedriver.exe")
driver = webdriver.Chrome(service=service)
driver.get(r"E:\Jobs\TCS\Testing\Selenium\TestingChrome\Test1\delayAlert.html")
wait = WebDriverWait(driver, 10);
delayAlert = wait.until(EC.alert_is_present());
alert = driver.switch_to.alert
print("Alert Text:", alert.text)
alert.accept()
print("Alert accepted successfully!")
driver.quit()

Action Chains

Action Chains in Selenium allow you to perform mouse and keyboard actions like hover, drag-and-drop, right-click, double-click, etc.

Html Script

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Action Chains Example</title>
    <style>
        #hoverText {
            display: none;
            color: red;
            font-weight: bold;
        }
        #hoverArea:hover + #hoverText {
            display: block;
        }
        #draggable {
            width: 100px;
            height: 100px;
            background-color: blue;
            color: white;
            text-align: center;
            line-height: 100px;
            cursor: grab;
        }
        #droppable {
            width: 120px;
            height: 120px;
            border: 2px dashed black;
            text-align: center;
            line-height: 120px;
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <h2>Action Chains Example</h2>
    <!-- Right Click and Double Click Example -->
    <button id="actionButton">Right Click or Double Click</button>
    <!-- Hover Example -->
    <div id="hoverArea" style="margin-top: 20px; background: yellow; padding: 10px; display: inline-block;">
        Hover over me
    </div>
    <div id="hoverText">You hovered!</div>
    <!-- Drag and Drop Example -->
    <div id="draggable">Drag Me</div>
    <div id="droppable">Drop Here</div>
    <script>
        document.getElementById("actionButton").addEventListener("contextmenu", function(event) {
            event.preventDefault();
            alert("Right-click detected!");
        });
        document.getElementById("actionButton").addEventListener("dblclick", function() {
            alert("Double-click detected!");
        });
    </script>
</body>
</html>

Selenium Code

import time
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By;
from selenium.webdriver.common.action_chains import ActionChains;
from selenium import webdriver;

service = Service(r"E:\Jobs\TCS\Testing\Selenium\Drivers\chromedriver.exe")
driver = webdriver.Chrome(service=service);
driver.get(r"E:\Jobs\TCS\Testing\Selenium\TestingChrome\Test1\actionChain.html")
actions = ActionChains(driver);
hoverArea = driver.find_element(By.ID,"hoverArea")
time.sleep(3);
actions.move_to_element(hoverArea).perform()
time.sleep(3);