DevQAExpert

Using  jQuery: contains Text Selector with Selenium in Java and Python

Locators like ID, class, and XPath are frequently used to interact with web items in Selenium-based web automation. However, there are situations when utilizing text content might be the simplest approach to find an element, particularly when other qualities are not distinctive or easily accessible. While jQuery has a built-in: contains CSS selector, which Selenium lacks, we may use it to improve our Selenium scripts in Java and Python.

With this article, we’ll look at how to use the jQuery’s`: contains` selector with Java and Python Selenium WebDriver scripts.

jQuery with Selenium as the Foundation

 

Why jQuery?

  • Ease of Use: When building client-side scripts for Selenium testing, jQuery offers a streamlined method of managing JavaScript events and actions.
  • Enhanced Selectors: jQuery adds a wealth of selectors to the table that Selenium does not natively support, such as: contains, allowing testers to build more adaptable and reliable locators.
  • Handling Ajax Requests: By utilizing jQuery, handling Ajax requests may be made simpler, making it simpler for Selenium scripts to handle dynamic material.
  • Cross-browser Compatibility: By normalizing browser differences, jQuery makes sure that your scripts function consistently across many browsers and offers a reliable Selenium testing environment.
  • DOM Traversal and Modification: When working with web components, jQuery’s fast DOM traversal and modification functionality is invaluable. 

 

jQuery integration with Selenium

The Injection Mechanism

You can dynamically create a script element, give it the jQuery URL, and add it to the header of a web page to inject jQuery into it. This makes it possible for the website to use all of jQuery’s features even if jQuery wasn’t originally there.

 

Version Compatibility: Make sure the jQuery version you inject is appropriate for the web page and does not interfere with any of its features.

 

Avoiding Conflicts: jQuery should be injected in a way that prevents conflicts with any JavaScript libraries that are already present on the web page.

 

Load Time : Before running any jQuery-based scripts, ensure that jQuery has fully loaded. putting wait techniques into practice or verifying jQuery.is Ready can guarantee that jQuery has completed initialization.

jQuery validation

To avoid reference issues in our scripts utilizing jQuery, it is crucial to verify that jQuery is either available or has been correctly injected into the web page before employing jQuery selectors.

 

Specific Case Applicability

Although jQuery offers a wide set of features, it’s important to assess each situation individually to decide whether using jQuery is appropriate. Due to their simplicity and direct contact with the browser’s API, native Selenium locators may be used for straightforward interactions.

 

Utilizing  jQuery :contains Selector

Inject jQuery: Verify if the selectors are available on the web page before using them. Inject it if it isn’t present.

Locate Element: Use Selenium’s Javascript Executor to run a jQuery script using the: contains selector.

Interact & Validate: Engage with the element, perform actions, and validate outcomes using assertions.

 

Java Sample Code for Selenium Setup and Execution

 

 Here is an example Java code for Selenium WebDriver that uses   jQuery’s: a text selection that may be used to interact with a web element

 

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;

public class CssCheck {
    public static void main(String[] args) throws InterruptedException {
        System.setProperty(“webdriver.chrome.driver”, “path_to_chromedriver”);

        WebDriver driver = new ChromeDriver();
        driver.get(“https://demoqa.com/buttons”);
        driver.manage().window().maximize();
        Thread.sleep(10000);

        // Ensure jQuery is available
        if (!isJQueryLoaded(driver)) {
            injectJQuery(driver);
        }
        Thread.sleep(10000);

        // Use jQuery to find an element with contains and get its text
        JavascriptExecutor js = (JavascriptExecutor) driver;
        String elementText = (String) js.executeScript(
                “return $(‘button:contains(Double Click Me)’).first().text();”
        );
        System.out.println(“Fetched text: “ + elementText);

        // Assert the text is as expected
        Assert.assertEquals(elementText, “Double Click Me”);

        driver.quit();
    }

    private static boolean isJQueryLoaded(WebDriver driver) {
        JavascriptExecutor js = (JavascriptExecutor) driver;
        boolean loaded;
        try {
            loaded = (Boolean) js.executeScript(“return jQuery.isReady”);
        } catch (Exception e) {
            loaded = false;
        }
        return loaded;
    }

    private static void injectJQuery(WebDriver driver) {
        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript(“if (!window.jQuery) {“ +
                “var jquery = document.createElement(‘script’); jquery.type = ‘text/javascript’;” +
                “jquery.src = ‘https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js’;” +
                “document.getElementsByTagName(‘head’)[0].appendChild(jquery);” +
                “}”);
    }
}

 

Explanation

  1. Ensuring jQuery is Available:

Before using jQuery selectors, we ensure jQuery is available on the webpage using isJQueryLoaded(). If not, it gets injected using injectJQuery().

 

if (!isJQueryLoaded(driver)) { injectJQuery(driver); }
  1. Locating Element Using jQuery :contains Selector:

We execute a jQuery script to locate the button containing the text “Double Click Me” and retrieve its text content.

 

String elementText = (String) js.executeScript( “return $(‘button:contains(Double Click Me)’).first().text();” );
  1. Assertion:

Lastly, we assert to ensure the fetched text matches our expectation, ensuring our selector works as intended.

 

Assert.assertEquals(elementText, “Double Click Me”);

Setup and Execution in Selenium with Python

Here’s how you might achieve similar functionality using Selenium WebDriver with Python:

 

from selenium import webdriver
import time

driver = webdriver.Chrome(‘path_to_chromedriver’)
driver.get(‘https://demoqa.com/buttons’)
time.sleep(5)

# Ensure jQuery is available
if not driver.execute_script(‘return window.jQuery’):
    # Inject jQuery
    driver.execute_script(‘var jq = document.createElement(“script”);’ +
                          ‘jq.src = “https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”;’ +
                          ‘document.getElementsByTagName(“head”)[0].appendChild(jq);’)
    time.sleep(5)

# Use jQuery to find an element with contains and get its text
element_text = driver.execute_script(
    “return $(‘button:contains(Double Click Me)’).first().text();”
)
print(f”Fetched text: {element_text}”)

# Close the driver
driver.quit()

 

Explanation

The Python implementation follows a similar logic:

  • Inject jQuery if it is not available.
  • Locate and interact with the web element using jQuery’s :contains selector.
  • Print the fetched text to the console.