Counting the occurrences of a text in a webpage using Selenium WebDriver

Hey there! I'm trying to figure out how many times the text "VIM LIQUID MARATHI" appears on a specific page using selenium webdriver in Java. Can anyone assist me with this?

In my main class, I've used the following code snippet to check if the text exists on the page:

assertEquals(true,isTextPresent("VIM LIQUID MARATHI"));

I also have a method to determine if the text is present or not:

protected boolean isTextPresent(String text){
    try{
        boolean b = driver.getPageSource().contains(text);
        System.out.println(b);
        return b;
    }
    catch(Exception e){
        return false;
    }
}

However, I am unsure of how to count the number of occurrences of the text...

Answer №1

One issue that may arise when using the getPageSource() method is that it could potentially return elements such as id's, classnames, or other code snippets that match a particular String, even if they are not visible on the page itself. A more reliable alternative would be to utilize the getText() method specifically on the body element, ensuring that only the actual content of the page is extracted without any HTML tags. This approach seems to align better with what you are seeking.

// Retrieve and store the text within the body element
WebElement body = driver.findElement(By.tagName("body"));
String bodyText = body.getText();

// Initialize count variable
int count = 0;

// Search for occurrences of the specific string
while (bodyText.contains("VIM LIQUID MARATHI")){

    // Increment count upon finding a match
    count++;

    // Move on to search for the next occurrence
    bodyText = bodyText.substring(bodyText.indexOf("VIM LIQUID MARATHI") + "VIM LIQUID MARATHI".length());
}
System.out.println(count);

The variable count now holds the total number of instances found in the text.

Answer №2

There are a couple of approaches you can take to accomplish this task:

int size = driver.findElements(By.xpath("//*[text()='text to match']")).size();

By using this method, the driver will locate all elements containing the specified text and provide the count.

Alternatively, you can also search through the HTML content as mentioned.

int size = driver.getPageSource().split("text to match").length-1;

This technique involves fetching the page source, dividing it based on the matching text, and then calculating the total number of divisions made.

Answer №3

One way to run a JavaScript expression with WebDriver is by using the following code:

((JavascriptExecutor)driver).executeScript("yourScript();");

If jQuery is implemented on your webpage, you can utilize jQuery selectors like this:

((JavascriptExecutor)driver).executeScript("return jQuery([proper selector]).size()");

In the [proper selector] placeholder, ensure to input the correct selector that matches the text you are seeking.

Answer №4

Experiment

int count = driver.findElements(By.partialLinkText("VIM MARATHI")).size();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to parse this source text using selenium in Python?

<iframe id="frameNewAnimeuploads0" src="http://www.watchcartoononline.com/inc/animeuploads/embed.php?file=rick%20and%20morty%2FRick.and.Morty.S02E10.The.Wedding.Squanchers.720p.WEB-DL.DD5.1.flv&amp;hd=1" width="530" height="410" frameborder="0" scro ...

Navigating through a series of URLs using Selenium

I am encountering difficulties with looping through a list of URLs using selenium. The problem seems to lie within the #Second Part section of my code. Currently, the length of the linklinkfin list is 9, but this number can fluctuate as more URLs are gathe ...

Appium is reporting a console error stating, "The specified search parameters were unable to locate an element on the page."

Having difficulty finding the element in my mobile app. ` public class Ovex { private static AndroidDriver driver; public static void main(String[] args) throws MalformedURLException, InterruptedException { DesiredCapabilities capabilities = n ...

Exploring the Depths: A Guide to Selecting Nodes in Java Based on Depth

In my current JSON representation, I have the following structure: { "total": "555", "offset": "555", "hasMore": "false", "results": [ { "associations": { "workflowIds": [], "companyIds": [], "ownerIds": [], ...

An issue with Selenium web scraping arises: WebDriverException occurs after the initial iteration of the loop

Currently, I am executing a Selenium web-scraping loop on Chrome using MacOS arm64. The goal is to iterate through a list of keywords as inputs in an input box, search for each one, and retrieve the text of an attribute from the output. A few months ago, I ...

What is the process for locating a file, opening, or generating a Google Sheet within someone else's directory using a service account?

I'm facing a situation where I have an account containing test result spreadsheets. To interact with these spreadsheets programmatically using Java and Google Drive API v3, I utilize a service account. However, I am struggling to create a spreadsheet ...

How can test case sequencing be controlled in Selenium TestNG without relying solely on the priority attribute?

If I have a test class with 10 tests, I can use the priority attribute to determine their order. Are there alternative methods for setting the priority of test cases? ...

Casting user-defined data types to JSON objects can be achieved using the `jason.simple` library

I'm facing an issue with type casting a user-defined data type, USERS, into a JSON Object. When I tried using .toString() to convert Users into a String, the output was unexpected and incorrect. I then considered converting it into a JSON Object and r ...

Mastering the art of Python to extract all XPATHs from any website

Is there a method to extract product listings from various websites without needing to manually loop through each XPATH? Some sites like Amazon and Alibaba display up to 10 products per page, while others may have 20. I am looking for a way to retrieve a ...

Converting Windows Identifiers to Human-Readable Text with the Power of Selenium and Python

I am aware that in order to retrieve the corresponding IDs of the currently open windows, I utilize the following code snippet in Python: current_windows = driver.window_handles print(current_windows) Output (assuming there are 2 open windows): ['CDw ...

What is the best way to execute multiple test cases using Selenium with Python?

import unittest from selenium import webdriver from datetime import datetime class Index(unittest.TestCase): @classmethod def setUpClass(cls): chrome_options = webdriver.ChromeOptions() prefs = {"profile.default_content_setting_values.notificat ...

Access to Begin Operation Rejected

While attempting to execute my test through Appium's server, I encountered the following error: Permission to start activity denied The goal was to run the Chrome app without requiring the APK file since it is already installed on my device. appPac ...

Having difficulty choosing an element with protractor's virtual repeat functionality

Initially, I successfully used ng-repeat to select an element. However, the developers have since implemented virtual repeat which has caused the following code to stop working: expect(stores.listStores(0).getText()).toContain('Prahran'); expect ...

Is it possible to extract the CSS path of a web element using Selenium and Python?

I am working with a collection of elements using find_elements_by_css_selector, and my next task is to extract their css locators. I attempted the following approach: foo.get_property('css_selector') However, it seems to be returning None. ...

Cannot launch Selenium Chrome driver

Having trouble launching Chromedriver even though I have the latest chromedriver.exe. Any suggestions? This is the error message I'm encountering: "C:\Program Files (x86)\Java\jdk1.8.0_101\bin\java" -Didea.launcher.port=75 ...

Encountering issues with the .exe file after the conversion from .py, specifically receiving the error message: "ModuleNotFoundError: no module named 'selenium'"

Can somebody lend a hand? I'm fairly new to Python and it seems like I might have made a mistake somewhere in my code. This is the error message I'm getting: Traceback (most recent call last): File "webScrapingTool.py", line 1, in &l ...

Encountering a failsafe issue while attempting to run selenium code

Encountered an error in the main thread: java.lang.NoClassDefFoundError: dev/failsafe/Policy at org.seleniumhq.selenium.http/org.openqa.selenium.remote.http.ClientConfig.<clinit>(ClientConfig.java:33) at org.seleniumhq.selenium.chrome_driver/ ...

Webdriver-driven distributed testing

From my understanding, grid allows us to distribute tests across multiple nodes. For example, if I have 4 test cases and 2 nodes (both with the same configuration of platform: Windows, browser: Firefox, maxSession=1, maxInstances:1), I would expect 2 test ...

What is the best way to retrieve all variable names from a JSON file?

Is there a way to extract an array of variable names from JSON data? For instance, if I'm given: { "Java": 20526, "Shell": 292, "Groovy": 213 } I aim to transform it into an array like this: String[] {"Java", "Shell", "Groovy"} Any suggestio ...

Issue: In the Selenium Java Eclipse environment, there is an error indicating that the variable "Driver"

Currently, I am in the process of familiarizing myself with Selenium for automated testing. I have managed to successfully complete all parts of the test case except for the final step which involves checking if an alert is present to confirm the transacti ...