Obtaining the text from an element in Selenium using JavaScript

I've been trying to figure this out, and it seems like it should be a simple task, but how can I extract the text from a table displayed in a browser?

When I use the "inspect" tool, the code snippet looks something like this:

<tr role="row">
  <th class="component-body-text" colspan="1"role="columnheader">### The Text I want ###</th>

While there is more content in the table, my focus is solely on retrieving that specific piece of text.

Would a method similar to this work:

await driver.findElement(By.className('component-body-text')).getText(); 

Unfortunately, this approach didn't yield results. Should I consider handling multiple elements within the table instead:

const sample = await driver.findElements(By.className('component-body-text')); 
sampleText = sample[0].getText();

I have experimented with both methods, but haven't had success yet.

Answer №1

If you are looking to retrieve the text The Text I desire, there are various Locator Strategies you can employ:

  • Utilizing className:

    await driver.findElement(By.className("component-body-text")).getText();
    
  • Employing css:

    await driver.findElement(By.css("tr[role='row'] > th.component-body-text[role='columnheader']")).getText();
    
  • Using xpath:

    await driver.findElement(By.xpath("//tr[@role='row']/th[@class='component-body-text' and @role='columnheader']")).getText();
    

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

Leveraging regular expressions to target elements with dynamic numerical values embedded within xpath patterns

Within my application, I encounter emails in the inbox with unique IDs. Unfortunately, clicking on the first email is proving to be a challenge due to the constantly changing mail ID. The specific xpath looks like this: //*[@id='r1295']/td[4]/a ...

Activate automatic click or force trigger JavaScript function

In the MVC view I am working with, there is a form that allows for file submission. //Submit file <% using (Html.BeginForm("MethodName","ControllerName", FormMethod.Post, new { enctype = "multipart/form-data"})) { %> <input type=" ...

Is it possible for me to choose to establish a new scope within a directive?

Encountered an issue while reusing a directive where some tags had a second directive with a new scope created using new or {}, while others did not have one. Attempting to create a new scope when one already existed resulted in an error being thrown by An ...

Is it possible for the sum to turn into NaN in Bootstrap Table JavaScript?

I used bootstrap to create a table that links with phpmyadmin. I need to show the total current amount in the table, which should update when using the search function. However, I keep getting NaN as my result. Below is the relevant code: // PART OF CODE ...

What separates the act of returning an action from returning the entire function within a Page Object structure?

When it comes to Page Object, how does returning an action differ from returning the entire function? this.download = function() { element(by.id('modal-download-button')).click(); return this; }; Compared to this.download = function() { ...

Displaying the scope in HTML from a custom Angular directive: A step-by-step guide

Just getting started with angular js and I have a question. Is there a way to show the values of e.width and e.height in an HTML document? Can I utilize the scope within this context? .directive( "cropping", [function ($scope) { return { rest ...

Display text on the screen with a customized design using JavaScript's CSS styles

I need help with printing a specific page that contains some information designed in print.css. I want to print this page, including an image, with the same style. function printContent() { var divContents = document.getElementById("terms").innerH ...

`Firefoxx border table glitch`

When attempting to open/close tables in Firefox using this link, unnecessary borders appear. One way to fix this issue is by implementing the following JS solution: setTimeout(function () { $table.css({'table-layout': 'auto'}) ...

Maintain the chosen month in every dropdown toggle div in angular 4

While displaying data using toggle options, I am facing an issue where if I click on a different month, all other greyed out headers are displaying the previously selected values. I am trying to figure out a way to keep the value under Selected month as i ...

Create a custom CSS style to replace the default jQuery hide() function

HTML <div class="adm-input" <?php if(!empty($admin_fee) || $admin_fee != "") echo "style='display:block'"; ?> id="fees-input"> <label>Admission Fees(<i class="fa fa-inr"></i>)</label> <div class="in ...

Eslint error: Attempting to assign to rvalue in ES6 function definitions

Currently, I have eslint configured like this: { "extends": "google", "installedESLint": true } When running lint on the following function: app.get('/', (req, res) => { console.log(req); res.send('hello world') }); I ...

Python and Selenium: Navigating dropdown menu options when an option is not visible

Need help with scraping data from the 2015 municipal elections in Colombia? I'm trying to extract information from this webpage: Visit here So far, I've successfully scraped the number of registered voters ("personas habilitadas") in the municip ...

Ways to access states from a Vuex store within a Vuetify list in VueJs

Here is a snippet from my Vue file: import store from '@/store' export default{ name: 'myList', data: () => ({ show: true, listContent: [{ name: '1', icon: 'pers ...

Using TypeScript to incorporate JS web assembly into your project

I have been attempting to incorporate wasm-clingo into my TypeScript React project. I tried creating my own .d.ts file for the project: // wasm-clingo.d.ts declare module 'wasm-clingo' { export const Module: any; } and importing it like this: ...

Having trouble with Node JS res.redirect() not functioning as desired?

I'm attempting to use res.redirect() to redirect to an external URL, but the host name isn't being replaced. For example: My current URL: https://example.com Desired redirect URL: When I use res.redirect("https://example-2.com/pqr?par=123 ...

Is Material-UI suitable for a large-scale enterprise application?

We are in the process of transforming a massive and outdated MVC Java EE application into React. This particular application consists of a browser-based user interface with an extensive range of views that include intricate forms, listings, and links. It i ...

"A lengthy contenteditable div designed to mimic an input field, with the ability to horizontally scroll

When the input is too short for the entire text to be displayed, users have the option to horizontally scroll the text inside the input by dragging with the mouse. Is there a way to implement this functionality in a contenteditable field that appears as ...

Welcome to the starting point of the WebDriver server for Internet Explorer 11

public static void main(String[] args) { // TODO Auto-generated method stub System.setProperty("webdriver.ie.driver", "D:\\Eclipse\\IEDriverServer.exe"); WebDriver driver = new InternetExplorerDriver(); driver.get("http ...

Steps to resolve the issue: The current experimental syntax 'classProperties' is not supported

I encountered an issue where the experimental syntax 'classProperties' is not supported when trying to run my react js application. My goal is to increment the value inside a <span> when a ` button is clicked. Below is the excerpt of my c ...

Is it possible to create a lengthy Selenium script for a task that requires extensive time to run?

Situation Overview My website offers advertising opportunities for companies, allowing them to set start and end dates for their advertisements. However, the challenge lies in ensuring that the ads remain inactive until the specified date. Testing with S ...