What is the best method for extracting [object Text] using XPath?

I'm currently working with Selenium and attempting to extract text from a node that contains the keyword "approved," but I'm unsure of how to retrieve and validate this specific text.

Here is the node structure -

<div class="Notification-body">
    <div class="">
        <div class="type--primary u-textBreak">
            <span class="u-inline">
                <span class="type--title">User Name</span> approved "Page_For_Submission"
            </span>
        </div>
        <span class="u-displayBlock type--note">4 hours ago</span>
    </div>
</div>

Initially, I attempted using this XPath but it did not return any results -

(//span[contains(@class,'title')]/following-sibling::text()[contains(text(),'approved')])[1]

This indicates that it's not a simple text node.

Afterward, I tried these XPaths and successfully identified the element position

(//html/body/div[7]/div[3]/div[2]/div/div/div/div/ul/li[2]/a/div/div/div/div/span/text())[2]
//span[contains(@class,'title')]/following-sibling::text()
(//span[contains(@class,'title')]/following-sibling::text()[contains(.,'approved')])[1]

However, when using these XPaths in Selenium

System.out.println(driver.findElement(By.xpath(prop.getProperty("txt_approvedNotification"))).getText());

An error occurs during execution:

org.openqa.selenium.InvalidSelectorException: invalid selector: The result of the xpath expression "(XPath of Element)[2]" is: [object Text]. It should be an element.
  (Session info: chrome=77.0.3865.90)
Build info: version: '3.11.0', revision: 'e59cfb3', time: '2018-03-11T20:26:55.152Z'
System info: host: '*****', ip: '*****', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_191'

Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 77.0.3865.90,

I am curious whether this issue stems from a problem with the XPath or a limitation of the Selenium driver.

Answer №1

While Selenium lacks the ability to wrap a specific text node into a WebElement, a viable solution is to utilize JavaScript code to locate the desired text node, encapsulate it within a tag with a unique identifier, and then append it to the DOM. Subsequently, you can access this element using Selenium (findElement(By.id())).

For more information, please refer to

Answer №2

Even though you have already accepted a solution, I wanted to offer a simpler alternative. You can simply access the parent element and check if the text "approved" is present in it. Below is an example code snippet in C# using NUnit for the assertion. If needed, you may need to modify the locator to ensure that the element is uniquely identified. However, the main idea here is to verify that a specific string exists within a specific element.

StringAssert.Contains("approved", driver.FindElement(By.CssSelector("span.u-inline")).Text, "Ensure that X was 'approved'.");

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

Unable to fetch any links through the driver.find_elements method using the href attribute

As a newcomer to Python and Selenium WebDriver, my goal is to verify all links on my webpage by checking their HTTP status codes to identify any broken links. The snippet of code I am currently using looks like this... from selenium import webdriver from ...

Having trouble with enter key input not triggering?

I have scoured various resources for answers to my query, including Stackoverflow. Unfortunately, none of the posts I came across have helped me resolve my issue with getting the enter key to work in my project for FreeCodeCamp on Codepen. When I press the ...

Tips for testing a polling javascript ajax call using Selenium Java WebDriver

I am facing an issue with my JavaScript code on a page that continuously polls an API and updates an element in the HTML every second. I need to test this functionality using Selenium WebDriver, but I'm unsure how to handle the polling aspect of the J ...

What could be causing the incorrect updating of React State when passing my function to useState?

Currently, I am in the process of implementing a feature to toggle checkboxes and have encountered two inquiries. I have a checkbox component as well as a parent component responsible for managing the checkboxes' behavior. The issue arises when utiliz ...

Creating and Managing Excel Files using Java

package demo; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import java.io.FileInputStream; import java.io.FileOutputStream; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.xssf.usermodel.XS ...

What's causing this element to overlap the previous one (apologies, once more)?

This is the code: <form id="the_form" action="">ev </div> <!-- final pay_block --> <div class="linea"/> <div class="spacer"/> The "linea" element is currently overlapping the buy button because a margin-bottom of 15px has be ...

Discovering instances of a specific string within a larger string

My goal is to customize the default behavior of the alert function. Below is the code I am using: window.alert=function(txt) { waitOk='wait'; setMsgBox(txt); btnMsgOk.focus(); } However, I need this functionality to vary ba ...

Choose the first and last div element in the selection

Is there a way to target the first and fourth div elements using the :nth-child selector for styling purposes? .main{ width:460px; height:240px; } .box{ width:100px; height:100px; background:red; float:left; margin:10px; } /*I tried */ . ...

What are some effective techniques for developing a script to automate a straightforward task with selenium?

Hey there! I'm just starting out on my coding journey and I have a cool project idea. I heard about this guy who wrote a script to send a text to his wife when he was working late, and I want to do something similar. Basically, I need a script that c ...

Troubleshooting problem with iPhone X responsiveness

Struggling with responsive issues on iPhone X. Issue is only appearing on actual device. Any tips for fixing this? I'm facing an issue where the website looks good and responsive on all devices in Chrome's responsive view. But when I access it th ...

Utilizing a single controller in multiple locations within AngularJS

I am currently working on developing an Ionic application which includes screens with lists containing checkboxes and the option to select all items. My experience with AngularJS and Ionic is fairly limited. The "Select All" functionality works as intende ...

The tab content in VerticalTab Material React UI is spilling out and overflowing

Having some trouble with this particular component. Whenever I input content larger than my Grid size, it overflows the VerticalTab section. You can see an example of this in this codesandbox. Here's what I've attempted: return ( <div cla ...

Is there a way to successfully press a button on a website?

While testing, I start by navigating in the constructor webBrowser1.ScriptErrorsSuppressed = true; webBrowser1.Navigate("http://www.tapuz.co.il/forums/forumpage/393"); webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted; Next, in the DocumentC ...

What is the best way to delay entering data manually into a text box using Selenium WebDriver?

Is there a way to manually enter the captcha text? How should I write the code for this? Below is the code snippet I have: driver.findElement(By.name("/atg/commerce/order/purchase/CommitOrderFormHandler.userCaptcha")).sendKeys(captcha); However, I am en ...

What sets the Virtual DOM apart from the Shadow DOM?

During my exploration of Vue.js, I delved into the realm of shadow DOM to grasp the essence of a fundamental Vue.js Component. As I studied shadow DOM and its similarities to virtual DOM, I embarked on a quest for diverse information pertaining to both con ...

Combining two arrays in JavaScript and saving the result as an XLS file

I have a question that I couldn't find an answer to. I need to merge two arrays and export them to an Excel file using only JavaScript/jQuery. Let's say we have two arrays: Array 1 : ["Item 1", "Item 2"] Array 2 : ["Item 3", "Item 4"] When the ...

Limit the display of an element to a single occurrence by utilizing jQuery cookies

I have a unique piece of HTML and JS code that showcases an eye-catching modal box. This remarkable feature is present on every page of my website. However, to enhance the user experience, I would like to ensure that this div element is displayed only once ...

Evaluate a tooltip by hovering the mouse using the Selenium driver

As a newcomer to using Selenium for testing, I am facing an issue with testing tooltips on a pie chart. Here is the code I am working with: <g class="p0_tooltips"> <g id="p0_tooltip0" class="p0_tooltip" style="opacity: 0;" transform="translate(1 ...

The responsiveness issue with the Bootstrap button menu in my Django project is causing functionality problems

I am currently working on a Django project and have set up a static folder in my "accueil" application. However, when I resize the browser window, the button to show the menu does not function as expected. The template I downloaded for free is not working ...

Tips for optimizing the page speed of your Pixi JS app by ensuring it runs efficiently after the page loads

On my website, I implemented a dynamic gradient animation with shape-changing blobs using pixi js. The animation functions flawlessly, but the issue arises when I run page speed tests - the test assumes that the page has not finished rendering because the ...