The xpath property "text()" does not seem to be functioning as expected with a textnode in the code provided for Selenium

Snippet of HTML Code:

<div class="content">
  <div id="tab">
    <div class="row">
      <div class="col-sm-12">
        <div>
          <div>
            <div>
            </div>
            <div>
              <p><span>01</span></p>
              <p class="className"><span id="">parent</span>
                Child 
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

The challenge is to locate "child" within the HTML content, separate from "parent":

//*[@id="tab"]/div/div/div[1]/div[1]/div[2]/p.span

While locating "parent" works fine with the above query, isolating "child" proves challenging. Attempts have been made using various methods without success:

//*[@id="tab"]/div/div/div[1]/div[1]/div[2]/p/text()
//*[@id="tab"]/div/div/div[1]/div[1]/div[2]/p/text()[contains(.,'child')]

Interestingly, these queries yield results in online editors but return an "element absent on the page" error in a Java IDE.

Any insights or recommendations would be greatly appreciated!

Answer №1

Even though both the elements labeled as parent and child exist within the same <p> tag with a class attribute named className, it's important to note that the element containing the text "parent" is considered a descendant <span> node, while the one containing the text "child" is a descendant text node. Consequently, while Selenium can identify the element with the text "parent" using XPath v1.0, it may struggle to locate the text node associated with the text "child". Nevertheless, extracting the text from "child" is still feasible.

As such, my inquiry was along the lines of "What specific actions are you planning to take with this text? Are you simply looking to extract it?"

To successfully extract the text from "child", consider employing the following method:

WebElement myElement = driver.findElement(By.xpath("//div[@id='tab']//p[@class='className']"));
String myText = (String)((JavaScriptExecutor)driver).executeScript("return arguments[0].lastChild.textContent;", myElement);

Answer №2

When using xpath in Selenium, it's important to note that the text() function requires a TextNode to be returned. However, Selenium can only return an Element Node.

For instance, when you expect to find an Element Node with the tag name span at

//*[@id="tab"]/div/div/div[1]/div[1]/div[2]/p[2]/span
, Selenium may face limitations in providing this specific node.

Galen Framework integrates with Selenium for selecting elements on a web page and interacting with them during testing.

While browsers like DevTools may support

//*[@id="tab"]/div/div/div[1]/div[1]/div[2]/p[2]/text()
, Selenium does not offer direct support for returning text nodes through its find methods.

To work around this limitation, you can instruct Selenium to locate and return the p Element Node as shown below:

<p class="className"><span id="">parent</span>
    child
</p>

In Java, you can utilize the HTML DOM API to access specific nodes within an element, like retrieving the text value of a child node from a parent element.

((JavaScriptExecutor) driver).executeScript(
      "return arguments[0].childNodes[2].nodeValue;",
      driver.findElement(By.xpath(
          "//*[@id='tab']/div/div/div[1]/div[1]/div[2]/p[2]"
      ))
)
// arguments[0] refers to the p ElementNode
// childNodes[2] points to the 3rd child node (TextNode 'child') of the p element
// While you can directly interact with the text node using HTML DOM api,
// Selenium doesn't provide native support to return text nodes for further usage within Galen.

Answer №3

In my experience

"//p[contains(text(), 'uploaded')]"

is effective when using Selenium 3. However, as previously pointed out by yong, Selenium is limited to working with elements. In this case, you can utilize

element.getText();
element.getAttribute("textContent");

to retrieve the text contained within the paragraph.

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

Displaying postcode on a category page: A step-by-step guide

I would like to showcase the user input code and present it on the web exactly as entered. <?php #code... ?> Any assistance is greatly appreciated. Please excuse my English. Thank you! ...

Bidirectional updates in AngularJS with CSS styling

On the backend, certain HTML elements store their position and size persistently and retrieve them when the page loads. These elements can be dragged and resized by users, with any updates needing to be saved on the backend for consistency across sessions. ...

Getting the checked checkbox from a nested input using div and label in Selenium: How can it be done?

Here is the HTML block: <div class="formClass" style="line-height: 18px; display: block;"> <label id="randomId_34_30078" style="display: none; width:47%; margin-right: 5px;"> <input type=& ...

Give a response in ISO string

Hey everyone, I'm running into an issue when trying to access a date property in an array of objects from another component using props. When I try to convert it to a string using the 'toISOString()' method, I get an error saying 'toISO ...

sending a pair of variables via jQuery and AJAX

Having difficulty posting two variables using ajax and jquery when a button on a confirm window is pressed. Each variable can be displayed separately, but not both at the same time. UPDATE - Issue resolved. I overlooked including a necessary file. My mist ...

Waiting for Selenium to reload an element

Currently, I am working on a task where I need to achieve the following: The page I'm dealing with features a list of comments, with each comment being contained within a div. Additionally, there is a main container div that holds all these individua ...

Enhancing ag-grid with alternating row group colors following row span

My data structure is shown below: https://i.stack.imgur.com/fy5tn.png The column spanning functionality in ag-grid is working for columns 1 and 2 as expected. However, I am looking to implement alternate row colors based on the values in column 2 (animal ...

Guide to using Selenium and Python to automate clicking on a download button on a webpage that has a dynamically changing link based on the date

I am currently facing a challenge in my Python and Selenium project where I need to dynamically locate and download a file from a website. The issue is that the file I want to download has a date in its URL, and this date changes daily. Despite attempting ...

When attempting to utilize VueJs v-bind:type on an input element, it appears to be ineffective when the type property name is

Code: <!DOCTYPE html> <html> <head> <title>Creating a Vue app</title> <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3046455570021e061e0100">[ ...

Trying to set up automation for a HTML5 video using Selenium WebDriver and C# programming

The video doesn't have a specific ID since it's from YouTube. I've attempted to use a JavaScript executor to no avail. Here is the link: ...

Is it possible to select multiple three.js objects by pressing CTRL and clicking on each one

I'm having issues with implementing multiple selection of three.js objects using CTRL-click. While single-select works perfectly, the behavior is problematic when trying to select multiple objects with CTRL-click. The selected array sometimes contains ...

Tips for documenting the elements of an array in Javadoc

Imagine I have a matrix structured as follows: int[][] people = { { 20, 18, 22, 20, 16 }, { 18, 20, 18, 21, 20 }, { 16, 18, 16, 20, 24 }, { 25, 24, 22, 24, 25 }}; How can I provide infor ...

How can I retrieve an array of data from Firebase Firestore using React Native?

I have been working on fetching Array data from Firebase Firestore. The data is being fetched successfully, but it is all displaying together. Is there a way to fetch each piece of data one by one? Please refer to the image for a better understanding of ...

Java Implementation of Linked List Arrays

I am attempting to devise an array comprised of linked lists. The project I am endeavoring to undertake involves a string array filled with names, however some names coincide within the same position of the array. Take for instance if the name morgan is lo ...

Xpath is unable to process regular expression components

I'm new to using Selenium and XPath, and I'm trying to figure out how to make my code more dynamic. string exp = "//*[@id=\"g_1_bHwVovAN\"]/td[2]"; var dateTime = chromeDriver.FindElementsByXPath(exp); Currently, the code only retriev ...

Folding without extending

My button has a div inside it with content. I've set it up so that when the div is clicked, the collapsed content expands. The hover effect changes color and pointer as expected. But for some reason, clicking on the div doesn't expand the content ...

Oh no! An error occurred while running the Python program located at "D:pythonProjectwebscraping.py" on line 17. It seems to be related to the search function. Time to troubleshoot and fix this Python issue!

Currently, I am following a tutorial on YouTube about selenium and have encountered an issue at this stage. My code is functioning smoothly until it generates a significant error message: Traceback (most recent call last): File "D:\pythonProjec ...

Using Ajax to access the API variable through its URL attribute

My main goal is to configure a User ID and API Key within the URL for an Ajax call: Currently, I am doing: $.ajax({ url: "https://www.googleapis.com/plus/v1/people/115332174513505898112?key=AIzaFrCzbKLawSPG8C0tjZDozO1bSWx49mJm13s", context: document. ...

Selenium refusing to open a new website address

I am facing an issue with the code below where it should go to 3 URLs, but it only goes to 1. How can I fix this problem? Can anyone assist me with this? myURLs = ["https://google.com", "https://x.com", "https://cnn.com"] I h ...

I came across a fascinating finding during my JavaScript studies, but its origin remains a mystery to

I recently wrote some code and was surprised to find that it did not generate any output. Here is the snippet of code: var a1 = undefined; var a2 = 5; if(a1 > a2) alert(1); if(a1 < a2) alert(2); if(a1 >= a2) alert(3); if(a1 <= a2) ...