python LogoSelenium

Selenium is an open-source umbrella project for a range of tools and libraries that enables automation of web browsers. It provides a robust framework for automating interactions with web applications, primarily used for web testing, but also widely adopted for web scraping, browser automation tasks, and robotic process automation (RPA).

Key Components:
1. Selenium WebDriver: This is the core component of Selenium. WebDriver provides an API (Application Programming Interface) that allows you to write instructions to control web browsers directly. It communicates with browsers using browser-specific drivers (e.g., ChromeDriver for Chrome, GeckoDriver for Firefox, MSEdgeDriver for Edge). These drivers translate Selenium commands into native browser commands, enabling interactions like navigating to URLs, clicking buttons, typing text, selecting dropdown options, and executing JavaScript.
2. Selenium IDE: A Firefox and Chrome extension that allows you to record and playback interactions with a web browser. It's useful for creating simple test scripts quickly without writing code.
3. Selenium Grid: A system that allows tests to be run on different machines against different browsers in parallel. This significantly speeds up test execution time for large test suites and enables cross-browser, cross-platform testing.

How it Works:
When you write Selenium code (e.g., in Python, Java, C, Ruby), your script sends commands to the WebDriver API. The WebDriver then uses a browser-specific driver to interact with the chosen web browser. The driver then executes the commands on the browser (e.g., opening a URL, finding an element by its ID, clicking it). The browser responds, and the driver translates the browser's response back to the WebDriver, which then provides results to your script.

Advantages:
- Open Source: Free to use and has a large community.
- Multi-Browser Support: Works across Chrome, Firefox, Edge, Safari, and more.
- Multi-Language Support: APIs available for Python, Java, C, Ruby, JavaScript, Kotlin, and PHP.
- Cross-Platform: Runs on Windows, macOS, and Linux.
- Flexibility: Can interact with almost any web element and execute JavaScript.

Disadvantages:
- No Built-in Reporting: Requires integration with other tools (e.g., unittest, pytest, TestNG, ExtentReports).
- No Image Recognition: Primarily focuses on DOM-based elements.
- Complex Setup for Grid: Setting up Selenium Grid can be intricate.
- Doesn't Handle Desktop Applications: Limited to web browsers.

Example Code

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
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

 --- Prerequisites ---
 1. Install Selenium: pip install selenium
 2. Download a WebDriver for your browser (e.g., ChromeDriver for Google Chrome)
    and place it in your system's PATH, or specify its path when initializing the driver.
    Example: driver = webdriver.Chrome(executable_path="/path/to/your/chromedriver")


def run_selenium_example():
    print("Starting Selenium browser automation example...")

     Initialize the Chrome browser
     Assumes chromedriver is in system PATH or specified explicitly
    try:
        driver = webdriver.Chrome()
        print("Chrome browser launched successfully.")
    except Exception as e:
        print(f"Error launching browser: {e}")
        print("Please ensure chromedriver is in your system PATH or specified its path.")
        return

    try:
         1. Navigate to a website
        target_url = "https://www.google.com"
        driver.get(target_url)
        print(f"Navigated to: {target_url}")

         Verify the page title
        assert "Google" in driver.title
        print(f"Page title is: '{driver.title}' (Assertion Passed)")

         2. Find an element (the search box) and interact with it
         Wait up to 10 seconds for the search box to be present
        search_box = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.NAME, "q"))
        )
        print("Search box found.")

        search_term = "Selenium Python tutorial"
        search_box.send_keys(search_term)  Type text into the search box
        print(f"Entered search term: '{search_term}'")

        search_box.send_keys(Keys.RETURN)  Press Enter to perform the search
        print("Pressed Enter to submit search.")

         3. Wait for new page content to load and verify
         Wait for a search result element to appear, indicating the search completed
        WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.ID, "search"))
        )
        print("Search results page loaded.")

         Verify that the search term is in the new page's title
        assert search_term in driver.title
        print(f"New page title: '{driver.title}' (Assertion Passed)")

         4. Find and click another element (e.g., a specific search result link)
         This is just an example, the actual link might vary.
        try:
            first_result_link = WebDriverWait(driver, 10).until(
                EC.element_to_be_clickable((By.CSS_SELECTOR, "h3"))  Find the first h3, typically a link title
            )
            print(f"Clicked on: '{first_result_link.text}'")
            first_result_link.click()

             Wait for the new page to load (e.g., check for a different URL)
            WebDriverWait(driver, 10).until(EC.url_changes(driver.current_url))
            print(f"Navigated to: {driver.current_url}")

        except Exception as e:
            print(f"Could not find or click the first search result link: {e}")
            print("Proceeding without clicking a search result.")

         Optional: Take a screenshot
        driver.save_screenshot("selenium_example_screenshot.png")
        print("Screenshot 'selenium_example_screenshot.png' saved.")

    except Exception as e:
        print(f"An error occurred during the automation: {e}")
    finally:
         5. Close the browser
        driver.quit()
        print("Browser closed.")
        print("Selenium example finished.")

if __name__ == "__main__":
    run_selenium_example()