Searching for a specific text within an element using XPATH in C# with the Selenium framework

My current challenge involves locating specific text within certain elements on an HTML page.

<a class="ProductCard-link ProductCard-content" target="_self" tabindex="0" href="/en/product/puma-future-rider-menshoes/314207160004.html">
  <span class="ProductName"&gagt;
    <span class="ProductName-primary">
      Puma Future Rider
    </span>
    <span class="ProductName-alt">
      Men Shoes
        <span class="ProductName-separator">•</span>
      Black-White-Red
    </span>
  </span>
</a>

I am specifically interested in finding the text "Black-White-Red" within these elements. So far, I have successfully located the name of the shoe using this XPath:

//[@id='main']/div/div[2]/div/section/div/div[2]/ul[1]/li/div/a/span[1]/span[@class='ProductName-primary'][contains(text(), 'Puma Future Rider')]

However, my attempts to find the color of the shoe have been unsuccessful. I tried using the following XPath:

//*[@id='main']/div/div[2]/div/section/div/div[2]/ul[1]/li/div/a/span[1]/span[@class='ProductName-alt'][contains(text(), 'Black-White-Red')]

Surprisingly, this XPath did NOT work as expected. I find it strange that I can locate the "Men Shoes" text but not the color that is within the same tag:

//*[@id='main']/div/div[2]/div/section/div/div[2]/ul[1]/li/div/a/span[1]/span[@class='ProductName-alt'][contains(text(), 'Men Shoes')]

Thank you all in advance for any guidance or assistance you can provide! :)

Answer №1

the color and category can be found in the following:

if you locate this information and print it out, you will see:

Men Shoes • Black-White-Red

However, due to an element within the text, it will be recognized as two separate text nodes when using the text() xpath method.

You can confirm this by accessing the console in Chrome devtools and running the script below:

$x("//*[contains(text(), 'Men Shoes')]/text()") //this will display an array with two text nodes

$x("//*[contains(text(), 'Men Shoes')]/text()")[1].textContent //you can retrieve the content in this way;

https://i.stack.imgur.com/Yf4y3.png

As mentioned in the previous response, you can extract the second text node and compare it:

//*[contains(text()[2], 'Black-White-Red')]

You may also use:

//*[text()[contains(.,"Black")]]

In this case, text() looks for the first text node and returns all the text content within that node. '.' represents everything and checks for any instance of the word "black" in the array element.

Answer №2

Here is a suggestion:

//*@id='main']/div/div[2]/div/section/div/div[2]/ul[1]/li/div/a/span[1]/span[@class='ProductName-alt'][contains(text()[2], 'Black-White-Red')]

This solution should get the job done.

Remember, when dealing with multiple texts in the same attribute, make sure to specify the index accordingly.

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 title element is persistently appearing on the same line

As a beginner, I've created a document with a 3x3 checkerboard using HTML and CSS. However, I'm facing an issue where the heading element is not displaying on a separate line as expected. I believe the problem lies in the CSS styling, specifical ...

Having trouble locating and clicking an element using Selenium and Java

On the page, there is a specific button that needs to be clicked: <div _ngcontent-jnk-c107="" class="btn btn-primary btn-outline" tabindex="0" ng-reflect-router-link="/opportunity/1">VIEW</div> Identifyi ...

What are some methods to achieve consistent alignment of input fields across different mobile devices using CSS?

I have been working on a login page that looks good on desktop and laptop devices. However, I am facing an issue with its display on mobile devices. The design appears differently on various mobile devices - for instance, it looks acceptable on an iPhone 1 ...

PHP - Working with Regular Expressions in Improperly Formatted

Struggling with Regex has always been a challenge for me, especially when I need to extract content from a malformed piece of code like the option tag. The website where this code is obtained from has poor programming and inconsistent label structures: I& ...

The functionality of jquery .serialize is not effective when used on forms that are generated dynamically

Currently, I am utilizing Java/Spring within a .jsp file. The issue arises when attempting to dynamically load a form (including form tags) from myForm.jsp into a div in myPage.jsp and making an ajax post call with the data. Upon using jQuery .serialize a ...

change visibility:hidden to visible in a css class using JavaScript

I've put together a list of Game of Thrones characters who might meet their demise (no spoilers included). However, I'm struggling with removing a CSS class as part of my task. Simply deleting the CSS is not the solution I am looking for. I' ...

Place a div element immediately following a table row in the HTML document

Welcome to my hotel and cabin availability page! I've created a PHP query that displays the available hotels and cabins in a table format. However, I want to enhance the user experience by displaying a Google Maps location and some pictures of each ho ...

Error: Element at index 1 could not be found when using the select_by_index method in a Selenium loop with Python

On the page there is a selection box present, <div class="select select-gender select-container"> <select name="gender" class="my-dropdown 115px option" data-field="gender" data-type="dropdown"> <option value="female">Woman</opt ...

When scrubbing through videos, Chrome consistently throws a MEDIA_ERR_DECODE error

Encountering a MEDIA_ERR_DECODE error while scrubbing in Chrome on two different PCs. One PC runs Windows 7 with Chrome version 26, and the other runs Windows 8 with Chrome version 27. This issue occurs across all videos. When attempting to scrub on the v ...

Using jQuery, it is possible to eliminate a div element without affecting its contents

<div class="a"> <div class="b"> <ul> <li>Element A</li> <li>Element B</li> </ul> </div> </div> How can I eliminate div class="b" solely? I require the presence of div a, u ...

The communication factor that triggers the expansion of the mother element

I've been struggling with this issue for quite some time. Here is the challenge at hand: I am in the process of developing a library to streamline AJAX calls and neatly display error messages directly within a form. The dilemma: Whenever the messag ...

Creating an XML response to generate an HTML dropdown menu in PHP

My onChange function in javascript calls a PHP file to fetch UPS rates and update an HTML dropdown list. Everything was working fine until I needed to add an item to the options list based on a comparison. Javascript: function fetch_UPS(el){ var zip = ...

Experience the dynamic expansion of a droppable div as you elegantly drop an element within

When the questions "question1" and "question2" are dragged into "questionslots," I want the "questionSlots" div to expand its size dynamically when the second question is dropped into it. This means that both questions should be accommodated and visible wi ...

Deciphering the Mysteries of HTTP Headers

I have been using various applications to evaluate the quality of my websites, and many of the improvements suggested relate to missing http headers. Some examples include Content-Security-Policy, Charset, etc... I decided to visit the Wikipedia page on ...

Load Form with Json Data from LocalStorage Key-ID to Auto-Populate Fields

After successfully setting the ID in localStorage, I now need to retrieve and display only that specific record from my JSON data. The content of my localStorage is: This information is obtained from my JSON data after a button click. The challenge is us ...

Steps for implementing a conditional statement to handle an empty string in HTML

I need to figure out how to display a different message if my string is empty. Can anyone help me with this? <div class="padding" id="dealBorder"> <pre id="informationDealText"><pan class="inner-pre" style="font-size: 24px; color: whi ...

Icon appearing outside the button instead of inside

Here's a button I'm working with: <button class="glyphicon glyphicon-option-horizontal" (click)="myFuncion()"></button> Recently, I updated my bootstrap library from version 3 to 4.2.1 and now the icon is no longer visible. I' ...

Ways to hide the value from being shown

I have integrated jscolor (from jscolor) to allow users to pick a color with an input field. However, I am facing issues in styling it as I'm unable to remove the hex value of the selected color and couldn't find any relevant documentation on av ...

A convenient method for converting horizontal columns into vertical columns on mobile screens without using <div> tags or setting a minimum width, perfect for email formatting

After experimenting with using <div> elements and applying a min-width attribute to an email, I have come to the conclusion that these methods do not yield satisfactory results. While the alignment of horizontal columns works well on desktop screens, ...

Why won't my sticky element function properly with the position attribute set to sticky?

Hey there! I've been diving into learning all about CSS positions and have nailed down most of them. However, for some reason, the sticky position just won't cooperate and is stubbornly acting like a relative one instead. Check out my HTML snipp ...