Selenium xpath string comparisons are unsuccessful despite the strings being identical

In my framework, I am using a combination of keyword-driven and data-driven approaches. The expected strings are retrieved from an Excel sheet while the actual strings are taken from the webpage. Interestingly, even when both variables print the exact same strings, the test script fails. It passes for strings without spaces like "Resign", but fails for strings with spaces like "Property Search". Below is the result which prints "PASS" until "Resign", after which it fails. Please ignore the numbers as they are used for debugging purposes. Additionally, the XPaths used in the result are included.

Result generated
By.xpath: html/body/div[2]/div/div[2]/ul/li[1]/ul/li[1]
Tool tip text present: Revals
Revals
1 By.xpath: html/body/div[2]/div/div[2]/ul/li[1]/ul/li[2]/a[contains(text(),'Managed Client Accounts')]
Tool tip text present: Managed Client Accounts
Managed Client Accounts
1
By.xpath: html/body/div[2]/div/div[2]/ul/li[1]/ul/li[3]
Tool tip text present: Resigns
Resigns
1
... (additional results listed) ...

Here is the code:

public String verify_Text(String locatorType, String value, String data){
       try
  {
     By locator;
     locator = locatorValue(locatorType, value);
     System.out.println(locator);
     WebElement element = driver.findElement(locator);

    // Get tooltip text
    String toolTipText = element.getText();
    System.out.println("Tool tip text present :- " + toolTipText);
    System.out.println(data);

    // Compare toll tip text

         if(toolTipText.contentEquals(data))
           {
               System.out.println("1");
              return PASS;

           }

   ... (rest of the method implementation) ...

catch(Exception e)
  {
     LOG.error(Executor.currentSheet + ":" + e);
     getScreenshot("verify_Link", data);
     System.out.println("3");
     return FAIL;
  }
  getScreenshot("verify_Link", data);
  System.out.println("4");
  return FAIL;

}

Answer №1

Successful line of code that resolved my issue

if(toolTipText.replaceAll("\\s+","").equalsIgnoreCase(data.trim().replaceAll("\\s+","")))

Upon using this code and debugging, I discovered that the data passed from the excel sheet contained spaces between two letters while the web element tooltip did not. This discrepancy was not visible when inspecting the element.

Before utilizing replaceAll("\s+","")

By.xpath: html/body/div[2]/div/div[2]/ul/li[1]/ul/li[5]/a Tool tip text present: ManageDashboard Manage Dashboard

After applying replaceAll("\s+","") and removing space from the data retrieved from the excel sheet

By.xpath: html/body/div[2]/div/div[2]/ul/li[1]/ul/li[5]/a Tool tip text present: ManageDashboard ManageDashboard

Answer №2

Unfortunately, my reputation score is not high enough to leave a comment, but I wanted to offer some suggestions:

One possible solution could be to trim the string, as there may be an invisible character causing an issue in one of the Strings.

if(toolTipText.trim().contentEquals(data.trim()))

Another option to consider is using normalize-space to eliminate tab, carriage return, and line feed characters.

/*/a[normalize-space() = 'Hello World']

Answer №3

At times, when extracting text from WebElements, they may contain unwanted leading or trailing spaces. To improve the comparison process, consider using:

toolTipText.trim().equals(data.trim())

If this method still doesn't provide the desired outcome, another approach is to eliminate all spaces from the strings before comparing them. Here's how you can do it:

toolTipText = toolTipText.trim().replaceAll("\\p{Z}", "");
data = data.trim().replaceAll("\\p{Z}", "");
toolTipText.equals(data)

By applying replaceAll in this way, a string like Outstanding AR would transform into OutstandingAR. While this may seem excessive, if it resolves the issue, it suggests that extra spaces in the string were causing the problem.

Answer №4

In my perspective, I believe your function is attempting to handle too many tasks and is unnecessarily complex for the straightforward task at hand. One potential issue could be your utilization of contentEquals() instead of equals().

Since you are working with Java, consider leveraging the JUnit library for handling various comparisons efficiently. By using this approach, you can simplify your code and employ snippets like the following:

String expectedTooltip = "some value from Excel";
By locator = By.cssSelector("#header > h1 a");
getScreenshot("verify_Link", expectedTooltip);
Assert.assertEquals("verify tooltip", expectedTooltip, getTooltip(locator));

Add a supporting function that directly retrieves the tooltip from the element identified by the given locator. It's best practice to avoid passing strings around and converting them to locators. The By class offers a more straightforward solution. Additionally, I included a .trim() method here to eliminate any extra spaces at the beginning or end of the string.

public String getTooltip(By locator)
{
    return driver.findElement(locator).getText().trim();
}

If you encounter challenges with string comparison discrepancies, it's possible that non-printable characters are present in some of these strings, requiring removal or substitution before performing comparisons. One technique to troubleshoot this is to iterate through each string, print the ASCII values for individual characters, and pinpoint where the deviations occur.

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 content within the div section is failing to align precisely in the center of the page

The headers and paragraphs inside the class "center" are not aligning to the center. I have attempted different code combinations but nothing seems to work. Here is my HTML code: It was copied from the Bootstrap website and edited for my project. [HTML c ...

Instructions for automating the process of accessing Facebook Messenger and sending a message using Selenium code

As a beginner in Selenium scripting using Java, I am currently experimenting with opening a chat box on Facebook and sending a message. While I have successfully managed to open the chat box through Selenium, I am encountering difficulty in typing into the ...

Numerous anchor links are present

Is it possible to eliminate the red lines between "google links" while keeping the border color as red? How can I achieve this? Here is the code snippet provided: <!doctype html> <html> <head> <title>Website</title> </he ...

Tips for extracting JSON data from test.properties file in the presence of other web elements

I have a set of WebElements stored in a test.properties file and I am struggling to read and extract all the JSON data from it. Can someone assist me in extracting all the JSON data from a properties file using Java? I have attempted various methods to re ...

Parsing a JSON request using Restlet

My goal is to create a basic observatory app for keeping track of books and other items using restlet. So far, I have successfully implemented some simple GET requests, but I am facing an issue with POST requests. The specific problem I am encountering is ...

Utilizing Struts 2 to Convert a String into JSP Content

In my action class, I have a String property called jspString that I use to generate the content for the resulting JSP. The issue I'm facing is that when I try to include another JSP page using the jsp:include tag, the content of that page is not show ...

Adjust the position of a child element to be just outside the boundaries of its parent element using CSS

I am facing an issue with 2 nested divs in my HTML code. The design requires the inner div to appear "on top of" the outer div, like this: (source: examplewebsite.com) Although I have applied CSS to both elements, including a negative top margin on t ...

Comparing Firebase Analytics setup in Kotlin and Java

Can someone explain why initializing Firebase Analytics in Kotlin doesn't require context, while in Java it does? According to the documentation: Java: mFirebaseAnalytics = FirebaseAnalytics.getInstance(context); Kotlin: firebaseAnalytics = Firebase ...

Combining Fields Using JPA Annotations: Is It Possible to Merge Two Fields into One Column in a Join Table?

I am facing a situation where I have two classes, a Route class and a BusStop class. The Route class 'Uses' two BusStop objects, one as the starting point and the other as the destination. I am looking to map this relationship through a join tabl ...

Display toolbar title on small screens in separate lines

Recently, I encountered an issue while using v-toolbar in my vue app. Despite my efforts, I couldn't find a way to split the title into multiple lines on small screens. Currently, it displays as "Secti...." on smaller devices. Can anyone assist me wit ...

Ways to incorporate the X-shaped spinner hamburger menu into your design

Hello everyone, I am looking to create a toggle menu that switches between X and hamburger styles when clicked. I have shared my menu codes below but I'm not sure how to achieve this effect. If anyone can help, I would really appreciate it. Here are ...

Removing an element from an array in MongoDB

I've been struggling to remove an element from an array in Java... Within my "emailsInApp" collection, I have the following data: { "_id" : "750afe", "list" : [ "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="08426760664 ...

Unable to input text into a visible Firefox web element using C# Selenium; input field remains unchanged

When using C# Selenium with Firefox, I am encountering an issue where the text input functionality is not working as expected. Here is the code snippet causing the problem: IWebElement dosar = driver.FindElement(By.XPath("//*[@id=\"Text5\"]")); ...

Error 404 encountered when attempting to send a JSON object to the server

I've been facing a problem while trying to send a JSON object to the server using AJAX calls. I keep getting a 404 Bad Request error. The issue seems to be related to the fact that I have a form where I convert the form data into a JSON object, but th ...

Executing test cases from multiple classes with prioritization in Selenium using TestNG

I have a specific requirement where I need to run test cases in a certain sequence across different classes and URLs. Here is the scenario: Class A TC1 Class B TC2 TC4 Class C TC3 The desired sequence for running these te ...

Converting to alphanumeric characters using JavaScript

Is there a way to efficiently encode a random string into an alphanumeric-only string in JavaScript / NodeJS while still being able to decode it back to the original input? Any suggestion on the best approach for this would be greatly appreciated! ...

Is it possible to change a Material UI style without resorting to an HOC?

Is there any method to modify the styling of a Material UI component without the need to create an entirely new component using withStyles()? For example, if I am currently displaying the following and simply want to adjust the color of the "Delete" label ...

DateTimeFormatter for the format of MM/yy

Whenever I attempt this action, an error occurs: LocalDate.parse(expirationDate,DateTimeFormatter.ofPattern("MM/yy"); java.time.format.DateTimeParseException: Text '09/14' could not be parsed at index 5 I have tried experimenting with the buil ...

What could be causing the malfunction of this *jquery.dataTables.js* demonstration?

Why is this DataTables.js example failing? Despite being a simple example, it encounters an exception when executed. -What could be causing the failure? (see below) (Is there something wrong with the code? -Or, what other factors can I investigate to i ...

Utilize CSS to prioritize the image and ensure it is responsive

I'm utilizing the 'featurette' feature in bootstrap. Currently, the page displays text on the left and an image on the right. As you reduce the browser size, they stack on top of each other, with the text appearing above the image. How can I ...