Guide on utilizing Selenium and Java to retrieve text within the DOM

I am trying to extract the text from the DOM structure but I am facing difficulties. I have tried using getText(); and getAttribute(); methods, but I am not able to retrieve the desired text. I have also experimented with values like inner HTML, outer HTML, and text within the getAttribute(); method, but still unable to get the required text. Can someone assist me in extracting it?

<label class="">
    <input type="checkbox" value="ml+4gvbuEG8Y3bBbAEbQvA==" name="selectedemployees" class="checkall">Alberta              Weekly1             
</label>

I am looking to display the text "Alberta Weekly1" in my console.

https://i.sstatic.net/U9zVg.png

Check Console output here

Answer №1

If you want to retrieve the specific text Alberta Weekly1, you will need to implement the use of WebDriverWait along with the method visibilityOfElementLocated(). Below is an example using the provided XPATH option.

WebDriverWait wait = new WebDriverWait(driver, 30);
String textValue = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//label[./input[@name='selectedemployees']]"))).getText(); 
System.out.println(textValue);

Answer №2

Another option to consider is using the following xpath:

//label//child::input[@class='checkall' and @name='selectedemployees']

Answer №3

If you want to retrieve the text Alberta Weekly1, you can do so by implementing a WebDriverWait for the method visibilityOfElementLocated(). Since the target node is a text node, you have the option to utilize the executeScript() function along with one of the following Locator Strategies:

  • xpath 1:

    System.out.println(((JavascriptExecutor)driver).executeScript("return arguments[0].lastChild.textContent;", new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//label[./input[@class='checkall' and @name='selectedemployees']]")))).toString());
    
  • xpath 2:

    System.out.println(((JavascriptExecutor)driver).executeScript("return arguments[0].lastChild.textContent;", new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//label/input[@class='checkall' and @name='selectedemployees']/..")))).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

What is the best way to display a landing page using an AngularJS web application?

As a newcomer to AngularJS, I am currently working on a small web application using ui-router for page routing. I have a landing page that consists of static content with clickable links covering the entire screen, while other pages only occupy the "ui-v ...

Using Google Colab for web scraping and encountering error related to webdriver not being callable while working with a module

I've been attempting to scrape hotel reviews from a website, but I'm facing an issue where the URL remains unchanged even when jumping to multiple pages. To resolve this, I turned to using the Selenium Webdriver. However, I encountered difficulti ...

Utilizing an automated file retrieval system in the absence of database or website access

I'm faced with a challenge of having to download a file automatically when a user clicks the "ok" button on a website. Unfortunately, I only have access to view the site and do not have access to the database or source code. I'm unsure of how and ...

Steps for altering the public folder in a Next.js project

In my monorepo, the structure is as follows: apps/ web/ - next.config.js - pages/ public/ The Next.js application is located in the apps/web/ directory. How can I modify the next.config.js file to instruct it to serve public assets from the root ...

Is there a way to incorporate an event into the legend of chart.js?

I've recently managed to incorporate an event based on this post, but unfortunately, it's not being triggered. Any thoughts on why that might be? For reference, I am utilizing the default chart.js legend. Chart.helpers.each(vm.chart.legend.legen ...

Utilizing a single JavaScript file for handling multiple PHP AJAX requests

Initially, my goal is to streamline my code by consolidating multiple ajax calls into a single JS file. I want these ajax calls, each referencing PHP files, to all utilize the same JS file without triggering additional requests that could slow down the pro ...

Remove the ID, class, and other attributes from an HTML string using JavaScript for sanitization purposes

Can someone help me with sanitizing HTML text provided by a user? The HTML code in question is as follows: var htmlStr = `<p id="test" class="mydemo">TEhis is test</p> <pre class="css"> &lt;html> &lt;body cl ...

Filtering with checkboxes (looking for help with logic functionality)

Yesterday, I sought assistance with a similar question and was able to make progress based on the response provided. However, I have encountered another issue that has left me stuck. Current behavior: Clicking on a checkbox changes the background color of ...

Looping to run an async process (sequilize.authenticate) multiple times until successful

I need my microservice to wait for the database to become available before proceeding. There is a sidecar Cloud SQL proxy involved that requires some time for the database connection. My current approach involves a for loop that retries connecting after a ...

Leverage the power of index to slice through an array in Apps Script

Having recently transitioned from Matlab to apps script, I am facing a challenge with subsetting arrays. Specifically, I need to filter the array "names" based on the values in another array called "index", which are of equal length: names = [["name1"], [ ...

Certain videos may display as a blank white screen on mobile devices when utilizing an HTML5 video tag

I'm currently working on a React app that allows users to upload videos from their devices. The uploaded video is then displayed on the webpage using a <video> tag. During testing, I encountered an issue where some specific videos would only sh ...

Experiencing problem with wiretap logging in Spring Webflux WebClient

Seeking assistance on using Java Spring Webflux WebClient and wiretap logging. I am currently working with Java utilizing SpringBoot Webflux WebClient 2.5.0 for making outbound http requests (as the source) to a target. An example of creating an outbound ...

Enhance your web forms with jQuery Chosen's automatic formatting feature

Having trouble adding a feature to my multi-select input box using jQuery Chosen. The current functionality allows users to enter custom values not in the list. The new feature should automatically format numbers entered by users, for example: User input ...

Utilize the UseQuery graphql function in conjunction with the useState hook within useEffect, allowing for the execution of an additional useEffect to update additional state

In my NextJS project, I am utilizing Apollo for graphQL queries and encountering an issue with the stateData.allProducts section. Despite setting the state in the useEffect and including data as a dependency in the array, the error claims it is null when d ...

Having difficulty in animating the upward movement of textbox2

I've got a form that contains 2 buttons and 2 textareas. When the form loads, I want to display only section1 (button, textarea) and the section2 button. Upon clicking the section2 button, my aim is to hide the section1 textarea, reveal the section2 t ...

I'm looking for the specific numeric keycodes that are compatible with the keyPress function in Selenium. Can anyone point

Check out for details on the keySequence parameter in the keyPress command: You can specify the key to be pressed as either a string (starting with "\" followed by the numeric keycode, usually the ASCII value) or a single character. For example: " ...

I am seeking advice on how to effectively use Selenium to select a radio button among three options. Despite my efforts, I am encountering errors in selecting

I'm currently developing a web portal that involves selecting a voucher type from three radio buttons. However, I have encountered an issue with my code and am receiving an error. import java.util.concurrent.TimeUnit; import org.apache.log4j.Logger; ...

Adjust the CSS of a different class when the :focus state is triggered

Imagine you have the following code snippet: HTML <div class="container"> <input class="myAwesomeInputBox"> </div> CSS .input [type=text]:focus > .//ANY CLASS SOMEWHERE ON THE WEBSITE{ //Some sweet CSS. } This code does not ...

What is the best way to trigger clearTimeout() from within setTimeout()?

I currently have a setTimeout function running to operate a watch, but I am looking to clearTimeout on this existing function when I click on a button. However, I want the clearTimeout to only occur after a few seconds. Essentially, I am trying to implemen ...

Using an external JavaScript script may encounter difficulties when loading pages with jQuery

Trying to utilize jQuery for loading html posts into the main html page and enabling external scripts to function on them. Utilizing a script (load.js) to load posts into the index.html page: $(document).ready(function () { $('#header').loa ...