Finding the text content of a text node in Selenium and Java when it is not enclosed within its own tag

Is there a way to extract just one line of text (like standard_user) from the list below?

<div id="login_credentials" class="login_credentials">
              <h4>Accepted usernames are:</h4>

              standard_user
<br>
              locked_out_user
<br>
              problem_user
<br>
              performance_glitch_user<br>

            </div>

Answer №1

Gather the text enclosed in a single div and divide them using line breaks:

WebElement block = driver.findElement(By.className("content"));
String[] contentLines = block.getText().split("\n");
System.out.println(contentLines[0]);

Answer №2

One way to approach this task is by reading the file line by line and implementing a condition to identify lines without any HTML tags.

if(!line.startwith("<"){ //add your code here}

Alternatively, utilizing a library that supports HTML file parsing based on your preferred programming language can simplify the process.

Answer №3

Text processing can sometimes be a bit tricky, especially when dealing with elements like <br> and partial text within them.

// start by extracting all text content from the div element
string allText = driver.findElement(By.id("login_credentials")).getText();

// extract the text of the H4 element for later removal
string textToRemove = driver.findElement(By.xpath("//div[@id='login_credentials']/h4")).getText();

// remove the unnecessary "Accepted usernames are:" part from the text
string filteredText = allText.Replace(textToRemove, "");

// split the filtered text by newline characters to get individual items that include 'standard_user'
string[] textArray = filteredText.split("\\r?\\n");

// retrieve the text corresponding to 'standard_user' which is the first item in the array
string standardUserText = textArray[0];

Although the last 3 lines could be condensed, I opted for this detailed version to elucidate each step's function.

Post execution evaluation, the allText variable should hold value:

Accepted usernames are: standard_user locked_out_user problem_user performance_glitch_user
.

With the removal of the Accepted usernames are: from the h4 element, filteredText contains:

standard_user locked_out_user problem_user performance_glitch_user
, separated by either \r or \n which necessitates regex handling.

Upon splitting filteredText at \n, we obtain an array:

[ "standard_user", "locked_out_user", "problem_user", "performance_glitch_user" ]

Subsequently, accessing textArray[0] retrieves the initial item from the list - likely to be standard_user.

Answer №4

Extract the content from the specified div and perform string manipulation to insert line breaks.

// Extract text from a specific div element using CSS selector 
String text = driver.findElement(By.cssSelector("div#login_credentials")).getText();

// Split the text into lines based on line breaks
String lines[] = text.split("\\r?\\n");

// Print out the second line of the extracted text
System.out.println(lines[1]);

Answer №5

The phrase standard_user refers to a text node within the <div> element. To retrieve the text standard_user, you can employ one of the following Locator Strategies:

  • Utilizing cssSelector:

    System.out.println((String)((JavascriptExecutor)driver).executeScript('return arguments[0].childNodes[2].textContent;', new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("div.login_credentials#login_credentials")))));
    
  • Employing xpath:

    System.out.println(((JavascriptExecutor)driver).executeScript('return arguments[0].childNodes[2].textContent;', new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@class='login_credentials' and @id='login_credentials']")))).toString());
    

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

Guide on how to update the controller value in AngularJS directive to trigger data retrieval

I currently have multiple controllers responsible for fetching data from the server. One example of such a controller is shown below: var vm = this; var month = 1; loadStatusCount(); function loadStatusCount() { vm.summaryCount = [] ...

I am having trouble with updating an array in React useState. Every time I try to make changes, it keeps reverting back to the initial state. What could

My current task involves managing a state array called monthlyIncidents, which contains 12 numbers that need to be updated under certain conditions. I attempted to update the elements by copying the array, modifying the specific element, and then updating ...

Electron employee: Concealed BrowserWindow leads to delay in the interface

My worker runs in a hidden browser window and sends multiple requests simultaneously. However, these requests from the worker end up causing lag and freezes in the main browser window. Any suggestions for resolving this issue? ...

In the JavaScript example provided, do child classes inherit their parent class prototype?

Here's the code I'm working with: class Rectangle { constructor(w, h) { this.w = w; this.h = h; } } Rectangle.prototype.area = function () { return (this.w * this.h); }; class Square extends Rectangle { construct ...

What is the process of setting up Express as an API web server and integrating a custom document renderer as middleware?

I have developed a code generator and I want to be able to execute it on the server. The generator utilizes pure native ECMA6 JavaScript to render HTML markup, but it is transpiled to ES5 before runtime using Babel and WebPack. I am looking to use this on ...

Guide on transferring Vue form input data to Adonis controller through an http request

I have a Vue component that prompts the user to enter their email address. I've utilized v-model for data binding. <template> <input v-model="email" type="text" placeholder="Email" /> <button class="tiny">Send</button> ...

Create a small circle in the bottom left corner with a constrained size

I'm trying to create a circle at the top of the screen on mobile, similar to the image below. The circle should take up a percentage of space, with the rest of the content appearing against a blue background as shown in the image. However, I'm h ...

Is there a way for me to verify if I have already made an AJAX data request

I have an image gallery with thumbnails. When a user clicks on a thumbnail, an ajax request is fired. I want to prevent the ajax request from firing again if the user clicks on the same thumbnail and instead use the existing data. $.getJSON(url, function( ...

Incorporating list items in a React component is not functioning as expected

When I console.log(this.props), here are my props: list:Array(1): {user: "Jack Nicholson", userid: "5b684ed8d3eb1972b6e04d32", socket: "1c0-Jb-kxe6kzPbPAAAD"} However, despite mapping through my list and using the component <UserItem user={user.user} ...

Creating modules or classes in ExpressJS

I am in the process of defining a modules/class that will contain a list of methods. Each method will have an instance of a service such as loggers, promises, etc. What is the best way to ensure clean code while implementing this? Currently, my code incl ...

google data visualization api version

I am struggling to find a solution to my issue, possibly because it is relatively new. I utilize the method VisualizationUtils.loadVisualizationApi(java.lang.Runnable onLoad, java.lang.String... packages) from the google visualization api in two distinct w ...

Is there a way for me to retrieve the data inputted into this form using JavaScript?

Having some trouble with this code. Can someone help me figure out what's going wrong? function displayData() { var userInput; userInput = document.getElementById(userInputs.firstInput); alert ("You entered: " + userInput); } <form ...

Find the square root of an element in an array using the Java

Having two issues here. Take a look at my code snippet below: public class Numbers { public static void main(String[] args) { double[] tab = { 9.0, 27, 5, 77 }; System.out.println("array size: " + tab.length); for (int y = 0; ...

What could be causing the Monster model to not appear when using the glTFLoader in three.js on iOS?

-Details- three.js version : r84 (current version) Device : iPad Air2 iOS version : 10.0.2 Browser : Chrome, Safari -glTFLoader- URL : Monster -> NOT visible The rest -> visible Why am I asking this question? I have encountered a similar is ...

Message from Discord: Unable to access the property 'MessageEmbed' because it is undefined

Attempting to create a simple welcome message embed. Here is my main.js file without the login token: const Discord = require('discord.js'); const client = new Discord.Client(); const MessageEmbed = new Discord.MessageEmbed(); const prefix = &ap ...

What could be the issue with my code? (Threejs spotlight shadow)

I recently created a Three.js scene featuring two cubes on a plane. The spotLight I placed in the top-left corner is intended to look at the coordinates 50, 0, -50. However, I noticed that the shadows appear odd and the light does not seem to be focusing ...

Ways to recycle a profile in Selenium rather than creating a new one

When it comes to website auto login, manual login will store the cookie for 3 days before requiring another manual login. Using Selenium for auto login allows for multiple restarts throughout the day. After manually logging in with the profile, there sho ...

Finding the current scroll height in Selenium using Python

How can I retrieve the current scroll height in Selenium using Python? For example, if I have scrolled down the middle of Stack Overflow, I would like to know the current scroll height using Selenium in Python. Thank you for your help. I attempted the fo ...

Task ':app:transformClassesWithMultidexlistForDebug' could not be successfully executed

Hi there, I'm encountering an issue when trying to compile my project. The error message that keeps popping up is: Execution failed for task ':app:transformClassesWithMultidexlistForDebug'. A java.io.IOException is preventing the writing p ...

Using Ajax and JQuery to show a success message prominently

Currently, I have a fully functional flash system implemented in PHP to display a success message to the user once an entry is created in the database. In one of the forms on my website, there is a select field where users should be able to seamlessly add ...