send_keys Method

The send_keys() method in Selenium is used to simulate typing text into input fields or elements such as text boxes, text areas, or other editable elements in web pages. It can also be used to send special keys like Enter, Tab, or Arrow keys by using the Keys class from selenium.webdriver.common.keys.

Syntax:

element.send_keys("text to input")

Example 1: Sending text to an input field

from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get('https://www.google.co.in')

#
Locate the input field
input_element = driver.find_element(By.NAME, 'q')

#
Send text to the input field
input_element.send_keys("Python Selenium")

#
Close the browser
driver.quit()

Example 2: Using special keys (e.g., Enter key)

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get('https://www.google.co.in')

#
Locate the input field
input_element = driver.find_element(By.NAME, 'q')

#
Send text and press Enter
input_element.send_keys("search query", Keys.ENTER)

#
Close the browser
driver.quit()

Common Use Cases:

  • Filling forms by sending text to multiple input fields.
  • Simulating keyboard actions such as pressing Enter, Tab, or navigating using arrow keys.

Selenium Waits

Selenium is an incredibly useful tool for automating web testing, but dealing with web elements that load dynamically can sometimes be tricky. This is where Selenium waits come into play.

Understanding Selenium Waits

Selenium waits allow you to manage timing issues and ensure that your script interacts with elements only when they’re ready. In this article, we’ll explore the different types of waits in Selenium, how to use them, and why they are essential in building robust automated tests.

Why Do We Need Waits in Selenium?

One of the biggest challenges in web automation is dealing with dynamic content that loads at different speeds. If your script tries to interact with an element that hasn’t loaded yet, it can throw an error. To solve this, Selenium provides different types of waits to pause your script and give the page time to load before continuing.


Types of Selenium Waits

Selenium offers three primary types of waits to deal with dynamic web elements:

  1. Implicit Waits
  2. Explicit Waits
  3. Fluent Waits

Let’s break down how each of these waits works.


1. Implicit Waits Explained

An Implicit Wait tells Selenium to wait for a specific amount of time before throwing an exception if an element isn’t found. This is like setting a blanket timeout for all the elements in your script.

How Implicit Waits Work

When you set an implicit wait, Selenium will pause the script for the given time, say 10 seconds, until the desired element becomes available. If it finds the element within that time, it proceeds. If not, it throws an exception


2. Explicit Waits Explained

Unlike implicit waits, Explicit Waits let you specify certain conditions under which Selenium should wait. Instead of just waiting for an element, it waits for a specific condition, like “element to be clickable” or “element to be visible.”

How Explicit Waits Work

You can define a condition in your script, and Selenium will keep checking for that condition to be met before interacting with the element. You can set both the condition and the maximum wait time.


3. Fluent Waits Explained

Fluent Waits offer more control by allowing you to set a polling interval, which determines how frequently Selenium checks if the condition is met. This wait is a more advanced form of explicit wait.

How Fluent Waits Differ from Explicit Waits

While both are condition-based waits, Fluent Waits let you customize the wait by defining the frequency with which Selenium checks the condition. Fluent waits are useful when you expect a delay but don’t want Selenium to keep waiting unnecessarily.

Using Polling Intervals with Fluent Waits

Fluent waits allow you to set a polling interval, like checking every 500 milliseconds, and can also ignore specific exceptions while waiting, which adds an extra layer of control to your tests.


Code Examples for Selenium Waits

Here are some practical examples of how to use different waits in Selenium with Python.

Using Implicit Waits in Python

from selenium import webdriver
driver = webdriver.Chrome()
driver.implicitly_wait(10) #
Set an implicit wait of 10 seconds
driver.get("https://sqatools.in/dummy-booking-website/")

Using Explicit Waits in Python

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

driver = webdriver.Chrome()
#
Lauch chrome browser and open dummy website
driver.get("https://sqatools.in/dummy-booking-website/")

#
Wait up to 10 seconds for the element to be clickable
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.ID, "firstname"))
)
element.click()
driver.close()

Using Fluent Waits in Python

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.support.ui import FluentWait
import time

driver = webdriver.Chrome()
driver.get("https://sqatools.in/dummy-booking-website/")

#
Fluent wait example with a polling interval of 500 milliseconds
wait = WebDriverWait(driver, 10, poll_frequency=0.5, ignored_exceptions=[Exception])

#
Wait for an element to be clickable
element = wait.until(EC.element_to_be_clickable((By.ID, "element_id")))
element.click()
driver.close()



Dummy Booking Website

Dummy ticket websites provide different web elements to do the automation



Dummy Ticket Booking Website



Choose the correct option:

  • Dummy ticket for visa application – $200
  • Dummy return ticket – $300
  • Dummy hotel booking ticket – $400
  • Dummy hotel and flight booking – $500
  • Cab booking and return date – $600

Passenger Details


First Name

Last Name

Date of birth*

Sex*
Male Female




Number of Additional Passangers




Travel Details


One Way Round Trip



Delivery Option





How will you like to receive the dummy ticket(optional)

Email WhatsApp Both


Billing Details


























Most Visited Cities


Select Option City ID City Name Passengers
6001 Mumbai 1033
6002 Pune 2002
6003 Indore 3000
6004 Kolkata 5000
6005 Hyderabad 6000
6006 Orangabad 3456
6007 Delhi 5666









is_selected Method

The is_selected() method in Selenium is used to check whether a web element, such as a checkbox, radio button, or option in a dropdown, is currently selected or not. It returns True if the element is selected and False if it is not.

Syntax:

element.is_selected()

Example:

from selenium import webdriver
from selenium.webdriver.common.by import By

#
Set up the driver (assuming you're using Chrome)
driver = webdriver.Chrome()

#
Open a webpage with website example
driver.get('https://example.com')

#
Locate a checkbox or radio button element
checkbox = driver.find_element(By.ID, 'checkbox_id')

#
Check if the checkbox is selected
if checkbox.is_selected():
print("The checkbox is selected.")
else:
print("The checkbox is not selected.")

#
Close the browser
driver.quit()

Example with checkbox selection

from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()

driver.implicitly_wait(20)
driver.maximize_window()

#
Open dummy website on the browser
driver.get('
https://sqatools.in/dummy-booking-website/')

#
get check element
checkbox_element = driver.find_element(By.XPATH, "//table//tr[2]//input")

#
check is_selected status before selecting checkbox
print("is_selected status:", checkbox_element.is_selected()) # False

checkbox_element.click()

#
check is_selected status after selecting checkbox
print("is_selected status:", checkbox_element.is_selected() # True

#
Close browser
driver.quit()


Explanation:

  • element.is_selected() works primarily for form elements like checkboxes, radio buttons, and options within a <select> dropdown.

  • If the element is selected (checked for a checkbox, selected for a radio button or dropdown option), it returns True. Otherwise, it returns False.

This method is useful when you need to verify the state of form elements before taking further action.


is_displayed Method

The is_displayed() method in Selenium is used to check whether a web element is visible to the user on the webpage. This method returns True if the element is visible and False if it is hidden (e.g., using CSS display: none, visibility: hidden, or if it is outside the viewport).

Syntax:

element.is_displayed()

Example:

from selenium import webdriver
from selenium.webdriver.common.by import By

#
Set up the driver (assuming you're using Chrome)
driver = webdriver.Chrome()

#
Open a webpage with website URL
driver.get('https://www.google.com')

#
Locate the element (e.g., a button or div)
element = driver.find_element(By.NAME, 'q')

#
Check if the element is displayed
if element.is_displayed():
print("The element is visible on the page.")
else:
print("The element is not visible on the page.")

#
Close the browser
driver.quit()

Explanation:

  • element.is_displayed() returns True if the element is visible to the user.
  • This method can be useful when you want to verify if an element is present on the page and is currently visible (not hidden or collapsed).

is_enabled Method

The is_enabled() method in Selenium is used to check whether a web element is enabled or not. This is typically used to verify if an input element, button, or other interactive elements are enabled for interaction (e.g. if they are clickable or can receive input).

Here’s a basic example of how to use is_enabled() in Python with Selenium:

Example:

Explanation:

  • element.is_enabled() returns True if the element is enabled, and False if it is disabled.
  • You can use this method before interacting with elements like buttons or input fields to ensure that they are available for interaction.

find_element and find_elements methods

In Selenium, two commonly used methods to locate elements on a web page are find_element and find_elements . They allow you to interact with HTML elements like buttons, links, text fields, etc. Let’s break them down

find_element Method

The find_element method is used to locate a single web element on the page. It returns the first matching element it finds. If it doesn’t find the element, it will raise a NoSuchElementException.

Syntax:

  • By : Locator strategy (e.g., By.ID, By.XPATH, By.Name, etc.).
  • value: The value that matches the element you want to find (e.g., the element’s ID, name, class, or other attributes).

Example:

If you want to find an element by its ID:

Here, Selenium will locate the element with the ID username and send a text to it.

Common Locator Strategies for find_element:

  • By.ID : Finds an element by its ID attribute.
  • By.NAME: Finds an element by its name attribute.
  • By.CLASS_NAME: Locates elements by the class name.
  • By.XPATH: Locates elements using an XPath expression.
  • By.CSS_SELECTOR: Finds elements using a CSS selector.
  • By.TAG_NAME: Locates elements by their tag name (e.g., h1, input).

find_elements Method

The find_elements method is used to locate multiple elements on a web page. It returns a list of all matching elements. If no elements are found, it returns an empty list (instead of raising an exception).

Syntax:

elements = driver.find_elements(by, value)
  • Similar to find_element, but it returns a list of elements.

Example:

To find all elements with a specific class name:

elements = driver.find_elements(By.CLASS_NAME, 'product')
for element in elements:
print(element.text)

In this case, all elements with the class name product will be located, and their text content will be printed.

Key Differences Between find_element and find_elements:

find_elementfind_elements
Returns one element (the first match)Returns a list of matching elements
Raises NoSuchElementException if no element is foundReturns an empty list if no elements are found
Best for situations where only one element is expectedIt is ideal when you want to find multiple elements (e.g., list items, products)

Different Browsers Execution with Selenium

Selenium is an open-source tool that automates browsers. It’s widely used in web testing to simulate user interaction with a website across different browsers

Introduction to Selenium and Browser Automation

Selenium is an open-source tool that automates browsers. It’s widely used in web testing to simulate user interaction with a website across different browsers, ensuring that it functions correctly. From clicking buttons to filling out forms, Selenium makes it easy for developers and testers to automate these tasks using different browsers. This capability is vital for cross-browser compatibility testing to verify that a website works smoothly across various platforms.

With Python being one of the most popular programming languages, combining Selenium with Python provides a simple, yet powerful, solution for automating browsers. Let’s explore how you can execute Selenium scripts across different browsers using Python.

Popular Browsers Supported by Selenium

Selenium supports several browsers, ensuring you can automate tasks across multiple platforms. Here are some popular browsers supported:

  • Google Chrome: The most widely used browser, known for its speed and reliability.
  • Mozilla Firefox: Open-source, secure, and highly customizable.
  • Microsoft Edge: Built on Chromium, Microsoft’s modern browser.
  • Safari: Apple’s browser, mainly used on macOS and iOS.

Running Automation Scripts in Chrome Browser

Here’s an example of launching a website and interacting with it:

from selenium import webdriver
from selenium.webdriver.common.by import By

#
Launch chrome browser
driver = webdriver.Chrome()
driver.implicitly_wait(20)
driver.maximize_window()

#
Open google page on the browser
driver.get('https://www.google.co.in')

#
Send text to google search field
driver.find_element(By.NAME, 'q').send_keys('Selenium automation')

#
Click on search button
driver.find_element(By.NAME, 'btnK').click()

#
Close browser
driver.close()

Running Automation Scripts in Firefox Browser

from selenium import webdriver
from selenium.webdriver.common.by import By

#
Launch Firefox browser
driver = webdriver.Firefox()
driver.implicitly_wait(20)
driver.maximize_window()

#
Open google page on the browser
driver.get('https://www.google.co.in')

#
Send text to google search field
driver.find_element(By.NAME, 'q').send_keys('Selenium automation')

#
Click on search button
driver.find_element(By.NAME, 'btnK').click()

#
Close browser
driver.close()

Running Automation Scripts in Edge Browser

from selenium import webdriver
from selenium.webdriver.common.by import By

#
Launch Edge browser
driver = webdriver.Edge()
driver.implicitly_wait(20)
driver.maximize_window()

#
Open google page on the browser
driver.get('https://www.google.co.in')

#
Send text to google search field
driver.find_element(By.NAME, 'q').send_keys('Selenium automation')

#
Click on search button
driver.find_element(By.NAME, 'btnK').click()

#
Close browser
driver.close()

Combine Scripts to run with all Browser

from selenium import webdriver
from selenium.webdriver.common.by import By


browser_name = 'Chrome'
driver = None
"""
Launch different browser as per
the value of browser_name variable

"""
if browser_name.lower() == 'chrome':
driver = webdriver.Chrome()
elif browser_name.lower() == 'firefox':
driver = webdriver.Firefox()
elif browser_name.lower() == 'Edge':
driver = webdriver.Edge()

driver.implicitly_wait(20)
driver.maximize_window()

#
Open google page on the browser
driver.get('https://www.google.co.in')

#
Send text to google search field
driver.find_element(By.NAME, 'q').send_keys('Selenium automation')

#
Click on search button
driver.find_element(By.NAME, 'btnK').click()

#
Close browser
driver.close()

CSS Selectors in Selenium

CSS (Cascading Style Sheets) Selectors are patterns used to select the content you want to style. In Selenium, CSS Selectors find HTML elements based on their CSS properties

CSS Selector in Selenium and Its Methods

Selenium is a powerful tool widely used to automate web applications for testing purposes. However, within Selenium, one of the key elements that make your automation effective is the ability to locate web elements accurately. Enter CSS Selectors – an efficient, flexible, and reliable way to identify elements in Selenium WebDriver. In this article, we’ll dive deep into CSS Selectors and their methods in Selenium.

Introduction to CSS Selectors

CSS (Cascading Style Sheets) Selectors are patterns used to select the content you want to style. In Selenium, CSS Selectors find HTML elements based on their CSS properties.

Why Use CSS Selectors in Selenium?

CSS Selectors offer several advantages: speed, simplicity, and compatibility. They allow you to quickly and effectively identify web elements, even those deeply nested within HTML code. This makes them ideal for locating complex elements that other strategies, like XPath, may struggle with.

CSS Selector vs. XPath: Which is Better?

Both CSS Selectors and XPath are popular choices in Selenium, but which is better? XPath is often considered more powerful due to its ability to navigate through both forward and backward elements. However, CSS Selectors are faster, and for front-end web developers, they are more familiar. CSS Selectors also work more seamlessly across different browsers.

Types of CSS Selectors in Selenium

CSS Selectors come in various forms, each suited for different use cases.

Basic CSS Selectors

  • ID Selector
    The ID selector selects an element based on its unique ID attribute. For example: #username.
  • Class Selector
    The class selector targets elements with a specific class attribute, written as: .login-button.
  • Tag Selector
    The tag selector selects all elements of a particular type (e.g., div, h1). For example: div.

Advanced CSS Selectors

  • Attribute Selector
    This selector selects elements based on an attribute and its value, like [type=’text’].

    Examples:

    input[id=’password’]
    input[name=’username’]
    span[data-testid=’facebook’]

  • Substring Matches
    With substring selectors, you can target elements based on part of their attribute value. For example, a[href^='https'] matches all links that start with “https”.

    Examples:
    input[data-ui-name^=”input_text”]
    label[for^=”search_type_option”]
    button[data-ui-name^=”input_location_to”]

Methods to Use CSS Selectors in Selenium

Selenium provides methods to use CSS Selectors to interact with elements.

Finding Elements with findElement and findElements

  • findElement:
    This method returns a single WebElement that matches the CSS Selector.
  • findElements:
    Unlike findElement, this returns a list of all matching WebElements.

Differences Between findElement and findElements

findElement will throw an exception if no elements are found, whereas findElements returns an empty list in such cases, making it a safer option for handling multiple matches.

Writing Efficient CSS Selectors

Creating efficient CSS Selectors is essential to improving test speed and reliability.

Best Practices for Writing CSS Selectors

  1. Keep it Simple: Avoid overcomplicating your selectors with too many attributes.
  2. Use IDs and Classes: These are faster and more reliable.
  3. Avoid Directly Using Styles: Use functional attributes rather than style-related ones for better maintainability.

CSS Selector Examples in Selenium

Using ID and Class Selectors

Example for ID Selector:

driver.find_element(By.CSS_SELECTOR, "#username").send_keys("user123");

Example for Class Selector:

driver.find_element(By.CSS_SELECTOR, ".login-button").click();

Example for Attribute Selector:

driver.find_element(By.CSS_SELECTOR,"input[type='password']").send_keys("mypassword");

Example for Substring Selector:

driver.find_element(By.CSS_SELECTOR,"a[href^='https']").click();

XPath Fundamentals

XPath (XML Path Language) is a powerful query language used to select nodes from an XML or HTML document. In the context of Selenium, XPath is primarily used to locate elements in a web page. It provides a flexible way to navigate through elements and attributes in a document, even when no other locators like id, class, or name are available or unique

XPath Fundamentals

1. XPath Expression

  • An XPath expression is a string of characters used to navigate through the document’s structure (XML/HTML).
  • It works by selecting nodes in the document that match the given pattern.

2. Absolute XPath

  • Definition: An absolute XPath starts from the root node (i.e., the top of the HTML document) and specifies the exact path to reach the target element.
  • Syntax: Starts with a single slash / and navigates through each element in the hierarchy.
  • Example: /html/body/div[1]/div[2]/input
  • Pros: Simple to understand and write.
  • Cons: Very brittle— if the structure of the page changes, the XPath breaks easily.

3. Relative XPath

  • 1Definition: A relative XPath starts from anywhere in the HTML DOM structure and is much more flexible than an absolute XPath.
  • Syntax: Starts with a double slash // to indicate searching from anywhere in the document.
Example:   //input[@id='username']

In the above example, input is the tag name and id is an attribute of the web element.

  • Pros: Flexible and more resilient to page structure changes.
  • Cons: It can be slower if the XPath is too broad or inefficient.

Common XPath Methods and Functions

1. Basic Syntax:

  • //: Selects nodes in the document from the current node that match the selection, regardless of location.
  • /: Selects nodes relative to the immediate current node.

2. Selecting by Attribute :

  • Basic syntax : //tagname[@attribute=’attribute value’]
  • Select elements based on their attributes using the @ symbol.
  • Example: //input[@type=’text’]
  • Finds an <input> element where the type attribute equals “text”.

Here are a few XPath examples from the Facebook login page.

  • //button[@data-testid=”royal-login-button”]
  • //div[@id=’reg_pages_msg’]
  • //a[@data-testid=’open-registration-form-button’]
  • Basic syntax to write XPath with text method:
    //tagname[text()=’text value’]
  • Use text() to find an element based on its inner text.
    Example:
  • HTML code : <button class=’cotent’>Login </button>
  • Selects a <button> element that contains the text "Login".
  • XPath with attribute : //tagname[contains(@attribute,’attribute value’)]
  • XPath with text : //tagname[contains(text(),’text value’)]
  • contains() is used when only a partial value of the attribute or text is on UI.
  • Example 1: Contains in Attribute : //input[contains(@name, ‘user’)]
  • Finds an <input> element where the name of the attribute contains the word “user”.
  • Example 2: Contains in Text: //button[contains(text(), 'submit')]
  • Finds a <button> the element where the visible text contains the word “Submit”.
  • Combine multiple attributes to use and or or in XPath.
  • Example 1 : //input[@type=’text’ and @name=’username']
    Finds an <input> element where type is “textand name is “username“.
  • Example 2 : //input[@type=’text’ or @name=’username’]
    Finds an <input> element where type is “textand name is “username“.

6. Selecting by Index

  • XPath allows selecting specific instances of elements in a list using square brackets [index].
    Example: (//input[@type=’text’])[1]
  • Selects the first element of type “text“.
  • Another example: //div[@class=’example-class’][2].
  • Selects the second element with class “example-class“.

7. Parent-Child Relationship

  • Parent to Child: //div[@id=’parent’]/input
  • Selects the element that is a direct child of a
    element with id=”parent”.
  • XPath supports navigating parent-child and ancestor-descendant relationships.
  • Descendant (grandchildren and below): //div[@id=’parent’]//input.
  • Selects any element that is a descendant (child, grandchild, etc.) of the with id=”parent”.

8. Selecting Parent or Ancestor Nodes

  • Parent: //input[@id=’child’]/parent::div
  • Selects the parent of the element with id=”child”.
  • Ancestor: //input[@id=’child’]/ancestor::form
  • Selects the ancestor element of the with id=”child”.

9. XPath Axes

  • Axes refer to the relationship between nodes. These are useful for navigating around the document.
  • following: Select all nodes after the current node.
    //input[@id=’username’]/following::input[1]
  • Selects the first element after the with id=”username”.
  • preceding: Select all nodes before the current node.
    //input[@id=’username’]/preceding::div[1]
  • Selects the first element before the with id=”username”.
  • following-sibling: Select sibling nodes that come after the current node.
    //input[@id=’username’]/following-sibling::input
  • Selects the sibling the element that follows the with id=”username”.
  • preceding-sibling: Select sibling nodes that come before the current node
    //input[@id=’password’]/preceding-sibling::input
  • Selects the sibling element that precedes the with id=”password”.

XPath Examples in Selenium:

1. Selecting an element by ID using XPath

element = driver.find_element(By.XPATH, "//input[@id='username']")

2. Selecting an element by class name

element = driver.find_element(By.XPATH, "//div[@class='container']")

3. Selecting an element by text

element = driver.find_element(By.XPATH, "//button[text()='Submit']")

4. Using contains() in XPath

element = driver.find_element(By.XPATH, "//a[contains(text(), 'Login')]")

5. Selecting a parent element using XPath

element = driver.find_element(By.XPATH, "//span[@id='child']/parent::div")

Advanced XPath Concepts

1. Combining Multiple XPath Expressions

  • Sometimes, you may need to combine different XPath conditions to locate elements effectively. This can be achieved using logical operators like and and or.
  • Using and: Combines two conditions, and both must be true.
    //input[@type=’text’ and @name=’username’]
  • This expression selects an element where type is “text” and name is “username”.
  • Using or: Combines two conditions, where at least one must be true.
    //input[@type=’text’ or @type=’password’]
  • This selects all elements where the type is either “text” or “password“.

2. Working with Dynamic Elements

  • In many web applications, elements may have dynamically generated attributes (e.g., auto-generated id or class values that change with each page load). You can use partial matches with the contains() function to locate dynamic elements in such cases.
  • Example with dynamic id: //button[contains(@id, ‘submit-‘)]
  • This selects a element where the id contains “submit-“, useful when the full id changes dynamically. Handling Dynamic Classes: //div[contains(@class, ‘active-item’)]
  • Selects any element that contains the class “active-item“, even if the class attribute has multiple class names.

3. Handling Complex HTML Structures

  • Web pages often have deeply nested HTML structures, and finding elements buried several layers deep can be challenging. XPath can be used effectively to navigate through these structures.
  • Example with complex hierarchy : //div[@class=’container’]//ul/li/a
  • This selects any “<a>” element that is inside an <li> element, which is part of <ul> that is a descendant of a <div> with “container”
  • The // allows searching for elements within all descendants of the specified node, not just direct children.
  • Using position(): XPath also allows you to select elements based on their position in the document. (//div[@class=’container’]//ul/li)[2]

4. Working with Attributes that Don’t Have Values

  • Sometimes, elements may have attributes without values, or you may need to select elements based on the presence of an attribute, regardless of its value.
  • Example: //input[@disabled]
  • This selects all elements that have the disabled attribute, regardless of its value.

5. Navigating Between Sibling Elements

  • XPath supports navigating between sibling elements, which can be useful when dealing with repetitive structures, such as lists or tables.
  • Select the next sibling element:
    //div[@class=’current’]/following-sibling::div[1]
  • This selects the first element that is a sibling of the with class “current” and comes immediately after it.
  • Select the previous sibling element:
    //div[@class=’current’]/preceding-sibling::div[1]
  • This selects the first element that is a sibling of the with class “current” and comes immediately before it.

XPath Best Practices

1. Use Relative XPath over Absolute XPath

  • While absolute XPath can pinpoint an element based on the full path from the root node, it is highly prone to breaking when the structure of the page changes. Relative XPath, on the other hand, starts searching from anywhere in the document and is more resilient to changes.
  • Avoid: /html/body/div[2]/div[1]/form/input
  • This will likely break if there’s even a slight change in the layout.
  • Preferred: //form[@id=’loginForm’]//input[@name=’username’]

2. Optimize XPath for Performance

  • XPath can sometimes be slow, especially on large or complex web pages. Using efficient XPath expressions can improve performance.
  • Use Direct Conditions: //div[@class=’container’]//*[text()=’Submit’]
  • Instead of searching broadly with multiple conditions, try to narrow down your search by providing direct attributes or shorter paths.
  • Avoid Over-Using //: The // operator searches through all descendants and can be slower. Use it only when necessary and prefer a more specific hierarchy if possible.