A guide on extracting the text content from an anchor tag by using xPath() with a combination of selenium and Mocha

I have successfully chosen an <a> tag. My goal is to display the text of the anchor tag, but I am facing difficulties.

The technologies being used are selenium, mocha, javascript, and phantomJS

This is the detailed script:

var assert = require('assert');
var test = require('selenium-webdriver/testing');
var webdriver = require('selenium-webdriver');
var By = webdriver.By;
var until = webdriver.until;
var equals = webdriver.equals;

/*-------login details--------*/
var userAdmin = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8cffedfffbedf8cce1edf8fee5f4e2e1e9e8e5eda2efe3e1">[email protected]</a>';
var passAdmin = 'DarkPrince2012';

var userTradeshow = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="53393c3d3a133e323a3f3a3d32273c217d303c3e">[email protected]</a>';
var passTradeshow = 'Mithun@';
/*-----login details ends-----*/

/*---setting up credentials---*/
var passArgument = process.env.KEY; /*fetch value from the environment value;*/
console.log("You chose to enter as '"+passArgument+"'");
if(passArgument.toLowerCase().indexOf("admin")>-1)
{
    var username = userAdmin,
        password = passAdmin;
}
else if(passArgument.toLowerCase().indexOf("trade")>-1)
{
    var username = userTradeshow,
        password = passTradeshow;
}   
else
{
    var username = "",
        password = "";
}    
/*-setting up credentials ends-*/

test.describe('TrackRevenue Test', function() 
{
  test.it('should work', function() 
  {
        var driver = new webdriver.Builder()
                    .withCapabilities(webdriver.Capabilities.phantomjs())
                    .build();
        var loginFlag = 0;
        var baseUrl = 'http://saswatr3.ouh.co/login';
        var expectedTitle = "Track Revenue";
        var successMessage = "Welcome to the admin page!";
        driver.get(baseUrl);
        driver.getTitle().then(function(title) 
        {
            if(expectedTitle === title)
            {
                console.log("Verification Successful - The correct title is displayed on the web page.");
            }
          ...
        });
    driver.quit();
  });
});

1. Case 1: With e[0].text

The issue is with this part of the script.

driver.findElements(By.xpath("//a[contains(@class, 'user-name m-r-sm text-muted welcome-message')]")).then(function(e){
                        if(e.length > 0)
                        {
                            console.log("No. of elements :"+e.length);
                            console.log("Found The USerName : ");
                            console.log("Username : "+e[0].text);//this is the line with the issue. It prints undefined
                        }
                    });

The output shows that

console.log("Username : "+e[0].text);
is causing the problem.

...

Here's the HTML structure:

<ul class="nav navbar-top-links navbar-right">
   <li>
      <a class="user-name m-r-sm text-muted welcome-message" href="/profile/"><a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="72011301051306321f1306001b0a1c1f17161b135c111d1f">[email protected]</a></a>
   </li>
   <li>
     ...

Answer №1

Here is a possible solution:

driver.findElement(By.xpath("//a[contains(@class, 'user-name m-r-sm text-muted welcome-message')]")).getText().then(function(text){
                           console.log("Username : " + text);
                        });
  • Make sure to use findElement instead of findElements for the search operation
  • Extract the text directly before the function part

UPDATE:

In some cases, the object may not be truly hidden but also not within the viewport, which can result in an empty String when using gettext().
To verify, you can try the following workaround:

driver.findElement(By.xpath("//a[contains(@class, 'user-name m-r-sm text-muted welcome-message')]")).getAttribute("innerText").then(function(text){
                           console.log("Username: " + text);
                        });

Answer №2

You have utilized the plural findElements, resulting in a list of elements. Trying to access e.text from this list will not be successful as .text can only be used with a webobject.

To acquire the first match on the page, make use of the singular version: driver.findElement()

If you find yourself needing to extract the text of a single element within a list, employ e[0].text to retrieve the text of the initial element in the list.

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

The text feature for the Google Places API is not displaying properly within the MUI TextField

For address auto-generation, I am currently utilizing the Google Places API. I have a regular input tag in my HTML where users can type their input and see Google Places suggestions in the dropdown - all working perfectly. However, when I switch to using m ...

The method to disable the dropdown for a select tag in a Polymer Dom-module is not functioning properly

I need help modifying the country dropdown based on a value retrieved from backend code If the disabled_value is 0, I want to hide the dropdown and make it unselectable If the disabled_value is 1, I want to enable the dropdown for selecting countries &l ...

Updating state using props from Relay QueryRenderer

My React component includes a form for updating database records using the React-Relay QueryRenderer component like this: class Update extends Component { //constructor.. //some stuff render() { return( <QueryRenderer environ ...

What is the method to retrieve text from a div element with Webdriver-IO?

Is there a way to extract the value from the following HTML element using Webdriver-IO for automated testing? <div class="metric-value ng-binding" ng-style="{'font-size': vis.params.fontSize+'pt'}" style="font-size: 60 ...

Using external scripts that require access to the DOM and window object within a Javascript/Node.js Azure Function: Best practices

I am attempting to integrate external JavaScript into an Azure Function that uses the JavaScript/Node.js flavor. The external JavaScript library I need to use, Kendo, relies on a DOM and a window. To achieve this, I initially experimented with JSDOM, but I ...

First, open Firefox using Selenium, then switch over to Chrome and Internet

Can I execute my Selenium test on Firefox, Chrome, and Internet Explorer in sequence? What is the process for accomplishing this? ...

Utilizing an unknown provider in AngularJS constants: a guide

Can anyone help me figure out what's going on with this code snippet? var app = angular.module('myApp', []); app.constant('_START_REQUEST_', '_START_REQUEST_'); app.constant('_END_REQUEST_&ap ...

Can RethinkDB and Node.js/Express handle parallel queries with multiple connections?

Is there a more efficient method for running parallel queries with the RethinkDB Node driver without opening multiple connections per request? Or is this current approach sufficient for my needs? I'd like to avoid using connection pools or third-party ...

How to use Selenium with Python to verify a checkbox is not selected

I am encountering the following Page Source: 1. <li_ngcontent-shv-c123 mat-menu-item role="presentation" class="mat-focus-indicator dropdown-item mat-menu-item ng-star-inserted" tabindex="0" aria-disabled="false"& ...

Retrieving AJAX data in a Node.js environment

In my HTML application, I am utilizing AJAX to showcase the output on the same page after the submit button is clicked. Before submitting, I am able to retrieve the values passed in the HTML form using: app.use(express.bodyParser()); var reqBody = r ...

Verify whether the type of the emitted variable aligns with the specified custom type

Currently, I am in the process of testing Vue 3 components using jest. My main objective is to receive an emit when a button is clicked and then verify if the emitted object corresponds to a custom type that I have defined in a separate file. Below is an e ...

How to create flexible, non-url-changing layout states with angular-ui-router?

My Objective I am working with two different styles of display: "Normal": [ Header | Body | Footer ] - primarily used for most views "Discreet": [ Body ] only, centered on screen - ideal for states like login/register, errors etc. These display styles ...

Angular displaying undefined for service

I have created a service for uploading images to a server, and I am encountering an issue when calling this service from my controller. The error message indicates that the function 'uploadFileToUrl' is undefined. Below is the code for my servic ...

"Want to learn how to dynamically disable an input field in AngularJS when another field is selected? Find out how to achieve this using the

Hey there, I'm dealing with two input fields. Input field A is a drop-down menu and input field B. They both have the same value (same ng-model). My goal is to clear the second input field whenever the user selects an option from the dropdown. Can any ...

Activate PHP using javascript

My PHP script is designed to capture a user's IP address, current webpage, screen resolution, and Date/Time when they visit my website. To implement this tracking functionality on another website, I plan to insert the following line of code: <scr ...

There was an error message saying "Unable to locate property 'getElementById' in undefined"

I am facing an issue with a jQuery filter function, and the error message it's showing is: Cannot read property 'getElementById' of undefined function CheckFilter() { var input, filter, table, tr, td, i, searchFilter; input = ...

Steps to submit a JavaScript-generated output as the value in a form input field

I'm facing an issue that seems basic, but I can't seem to figure it out. I'm trying to create a binary string representing the 12 months of the year using 12 checkboxes: const checkboxes = [...document.querySelectorAll('input[type=check ...

Does jQuery mobile lack a back button feature?

Thoughts swirling in my mind: <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title></title> <script src="<?php echo base_url();?>/assets/js/vendor/modern ...

Slow loading time when switching between items in the drop-down menu from the Main Menu

Visiting my website at europebathroom.com, you will notice a horizontal main menu with dropdown functionality. When hovering over a menu item, the corresponding dropdown appears seamlessly. Yet, sometimes quickly touching another menu item unintentionally ...

Using Gmail with Nodemailer is throwing an error: "Cannot add property 'mailer' on a string with value 'SMTP'."

I am facing an issue with sending data from a form to my Gmail account. Whenever I click the submit button, I encounter the same error message repeatedly. Despite researching various problems related to nodemailer, none of them match the specific problem t ...