Retrieve the inner text value from the third child element of an HTML using Selenium in Java

Here is the HTML code snippet:

<h2 id="xyz" class="test">
  <button class="restore 1" value="test2" title="hello"> Line1 </button>
  <button class="restore 2" value="test3" title="click"> Line2 </button>
  I need this text
</h2>

To extract the text "I need this text" from the above code, you can try the following methods:

1.) Using xpath="//h2[@id='xyz']/text()" might result in an error.

2.) Try using xpath="//h2[@id='xyz']").innerText to get only "I need this text"

Answer №1

The Selenium API does not provide direct support for text nodes extraction. To extract only the text content from the nodes, you can create a helper function using JavaScript like the one below:

WebElement element = driver.findElement(By.cssSelector("#xyz"));
String text = extractTextFromNodes(element);
public static String extractTextFromNodes(WebElement element) {
    String SCRIPT = 
     "for(var arr = [], e = arguments[0].firstChild; e; e = e.nextSibling) " +
     "  if(e.nodeType === 3) arr.push(e.nodeValue);                        " +
     "return arr.join('').replace(/ +/g, ' ').trim();                     " ;

    WebDriver driver = ((RemoteWebElement)element).getWrappedDriver();
    return  (String)((JavascriptExecutor)driver).executeScript(SCRIPT, element);
}

Answer №2

When executing the getText() method on a By, it should actually be run on a WebElement:

WebElement h2 = driver.findElement(By.xpath("//h2[@id='xyz']"));
String wantedText = h2.getText();

Alternatively, it is recommended to directly use the ID:

WebElement h2 = driver.findElement(By.id("xyz"));

Note: The second option that retrieves the entire text like Line1, Line2, and so on is correct. The HTML structure seems to be flawed as it places buttons under the h2 tag. Therefore, it is advised to exclude the text obtained from these buttons.

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

Discovering the parent element based on knowledge of the child element

One method I used to identify a child was through text. Driver.FindElement(By.XPath("//span[contains(@class,'MyClass')][contains(text(),'MyText')]")); The issue arises when I need to click on the parent element. The element is genera ...

A method for selecting the checkbox in a mat-row that corresponds to a certain text with Selenium

I want to select the checkbox within a nested mat-row: <mat-row _ngcontent-dac-c252="" role="row" class="mat-row cdk-row ng-star-inserted"> <mat-cell _ngcontent-dac-c252="" role="cell" class=&quo ...

Having trouble selecting radio buttons in Internet Explorer with Selenium WebDriver

I am facing an issue where I cannot select the radio button using Selenium web driver. Here is the HTML code: <input name="PersonalDetails.Paperless" class="input-validation-error" id="Paperless" type="radio" data-val-required="Contract notes selectio ...

Dealing with a distinct dynamic identifier in a JSON structure - what's the best approach?

Exploring json handling for the first time using retrofit to interact with an API. The unique ID "f9dcf2ef-8647-46c1-b1cc-7e2bb6c3caa2" varies whenever the username in the URL {username} is changed. { "status": 200, "foundmatch": true, "requested": ...

Retrieving specific information from the Model and returning it as a JSON response using annotations

I am interested in receiving a JSON response with additional annotations. Currently, my JSON response looks like: { "id": 1, "startDate": [ 1993, 12, 12 ], "endDate": [ 2018, 11, 22 ], "totalDistance": 255, "totalPrice": 211 } How ...

The Gson library fails to properly format a singular variable extracted from a JSON string

I am currently facing an issue with converting a json format, which is an arraylist response from a rest webservice, into its corresponding java arraylist. Interestingly, out of the 3 variables in the json response, only 2 are successfully formatted into ...

Selenium web scraping yielding different results than displayed on the user interface

Last week, User @KunduK was generous enough to assist me in scraping a website to retrieve the address of a specific record. The record in question can be found at this link: We used the following code snippet: address=WebDriverWait(driver,10).until(EC.vi ...

When using Selenium WebDriver to locate an object, an error may occur stating that the result of the xpath expression is "[object Text]" instead of an element as expected

I am currently utilizing Selenium to validate the existence of specific text within a web page. Here is an example of how the HTML appears. <html> <div class="a-content"> <!--!-->==$0 " Text to Locate" <b ...

Tips for grabbing the following element locator path with Selenium?

I am working on a piece of code to download a CSV file. Here is the code snippet: chromedriver = "/usr/lib/chromium-browser/chromedriver" driver = webdriver.Chrome(chromedriver) driver.get('https://www.aemo.com.au/Electricity/National-Electricity-Mar ...

A guide to pressing the combination of shift + ctrl + s with Selenium

Is there a way to simulate pressing shift + ctrl + s in Selenium? I attempted it with the following code: Actions action = new Actions(driver); action.sendKeys(Keys.chord(Keys.SHIFT + Keys.CONTROL + "s")).perform(); However, an error is being thrown. ...

WebDriver: Error during compilation in custom wrapper classes for web elements and drivers

// Can I use my own custom elements instead of the predefined selenium web elements such as webElement and WebDriver? To achieve this, I have created two custom wrapper classes: // Custom wrapper for WebDriver package org.rsf.wrapper.driver; import org.o ...

Guide on how to generate a JSON array structure for a collection of Plain Old Java Objects (POJOs) utilizing the code

I've been searching for a solution to convert a list of POJOs to JSON. We've previously used Codehaus Jackson with Spring MVC. What I'm trying to achieve is not an AJAX call with the @ResponseBody action, but rather a utility method to conve ...

Print the countdown of elements on the Python page by subtracting a specified number from the total count of

I'm looking to implement a page count down feature in my Python script for each page it navigates to. Below are my attempts so far. How can I achieve the desired result? In order to easily keep track of my script's progress, I have used the (len ...

Issue Encountered: Unable to locate the class file for org.openqa.selenium.internal.Locatable

I am currently facing a build error in Eclipse while using Selenium and Maven to develop a project. The error message states: Cannot find the class file for org.openqa.selenium.internal.Locatable. Upon closer inspection, I realized that the version of Sel ...

A Simple Java Method to Locate Elements

I am curious about how to convert these 2 generic methods for Selenium in C# into a Java version, as I do not have any experience with Java: public static IWebElement ConvertMethodForJava(Func<IWebDriver, IWebElement> expectedCondtions, int timeou ...

Ways to capture user input with Selenium WebDriver in Java

I need to create a Java project that will fulfill the following use cases: Request URL from user: Display an alert window to prompt the user for the URL. If the user clicks "Cancel", the program should close. Open the provided URL in a browser: After ...

gson: customized fromJson method based on the data type

Apologies if this has been asked before, but I couldn't find the information I'm looking for. Here are the different message types I have: class AbstractMessage { int code; String token; } class ShareMessage extends AbstractMessage{ ...

The latest version of chromedriver.exe for .Net, version 2.36, is not functioning properly with chrome 64

Last year everything was working fine, but recently when I tried to run the program, I encountered an annoying error message: "chromedriver.exe has stopped working". The exception thrown was: OpenQA.Selenium.WebDriverException: 'An exception with a nu ...

Waiting for an Element to Become Visible in Selenium-Webdriver Using Javascript

When using selenium-webdriver (api docs here), how can you ensure that an element is visible before proceeding? Within a set of custom testing helpers, there are two functions provided. The first function successfully waits for an element to exist, howeve ...

Unable to locate element in the DOM using XPath

Having trouble retrieving an element from the DOM using XPath <input bsdatepicker="" class="form-control font-size-normal ng-untouched ng-pristine ng-valid" id="endDate" name="endDate" placement="top" type="text"> The value of the element is not p ...