Retrieving WebElements based on Text with XPath in Selenium Testing

I am trying to locate a WebElement using XPath based on its text content.

The specific WebElement I want to find is:

https://i.sstatic.net/ji1jJ.png

Here is the HTML of the element:

https://i.sstatic.net/AyAqo.png

The WebElement I am trying to access contains an input element.

Currently, I am using the following code:

driver.findElement(By.xpath("//*[normalize-space(text()) = 'Own Hotel']"));

This XPath expression does not find the desired WebElement, even though it usually works for other elements.

I have also tried this XPath expression:

By.xpath("//*[contains(text(),'Own Hotel')]");

However, this method did not return any results either. I need an exact match for the text content.

I am searching for a way to locate a web element by its text regardless of any other elements inside it. If there is a match with the text, I want to retrieve the WebElement.

Thank you!

Answer №1

When looking for text wrapped in a label instead of an input, consider using the following code snippet:

driver.findElement(By.xpath(".//label[text()[normalize-space() = 'Own Hotel']]"));

To understand more about this xpath pattern, check out the detailed explanation provided here

Answer №2

Check out the HTML snippet below:

The text content of the innerText Own Hotel in the <input> element has leading and trailing white-space characters. Because of these extra spaces, you can't simply rely on using the location path text():

text() selects all text node children of the context node


Instead, consider using the String Function string normalize-space(string?) like this:

driver.findElement(By.xpath("//*[normalize-space()='Own Hotel']"));

To enhance your search specificity, include the tagName and a unique attribute as shown below:

  • Using tagName and normalize-space():

    driver.findElement(By.xpath("//input[normalize-space()='Own Hotel']"));
    
  • Using tagName, and normalize-space():

    driver.findElement(By.xpath("//input[@name='ownHotel' and normalize-space()='Own Hotel']"));
    

Further Reading

Explore additional discussions on utilizing normalize-space() at:

  • How to click on a link with trailing white-space characters on a web page using Selenium?
  • How to locate and click the element when the innerText contains leading and trailing white-space characters using Selenium and Python
  • How to click on the button when the textContext contains leading and trailing white-space characters using Selenium and Python

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

Tips for positioning text below an image using HTML and CSS

Hey there, I've been working on a website that needs to match this design: https://i.sstatic.net/39bW3.png This is an image of what I have completed so far: https://i.sstatic.net/WyEC2.png Here is the code I've written: body { ...

Limiting the results of a subquery using the Criteria API

I am currently working on a query that resembles select * from Table a where a.parent_id in (select b.id from Table b where b.state_cd = ? and rownum < 100) and I am attempting to achieve this using the Criteria API. While I have successfull ...

Issues with Drop Down CSS on Laravel Blade files

In my view, I have included various drop down menus such as https://i.sstatic.net/0UHgE.png Click here to access I am struggling to display a border bottom. I have attempted to manually define border-bottom in the CSS of those elements but have not been ...

develop a secondary menu using cascading style sheets

Seeking assistance to design submenus with CSS. As a newcomer, I am struggling with this HTML code and need guidance. <div class="nav-collapse collapse"> <ul id="nav-list" class="nav pull-right"> <li><a hre ...

Is there a glitch in the Bootstrap v4 Navbar?

Encountering an issue with the default navbar example from Bootstrap's official website. The navbar is supposed to be full-sized and collapse when the screen size decreases. However, after implementing the code into my project, it appears as always co ...

Only the constructor with a single parameter will be displayed in the intent

Looking to initiate an action upon clicking a button, however encountering the issue of android studio displaying only one constructor! The aim is to utilize the constructor with two parameters in the following manner: view screenshot Intent intent = new ...

Executing the JavaScript code to open the modal dialog

I have created a Modal Dialog (popup) using only CSS3 on my asp page for user registration: HTML : <%-- Modal PopUp starts here--%> <div id="openModal" class="modalDialog"> <div> <a href="#close" title="Close" class="clo ...

Using JAXB to marshal a primitive data type of considerable length

When trying to marshal a long primitive type using JAXB, I utilized the @XmlJavaTypeAdapter annotation to adapt non-String types to Strings. However, I encountered an error when attempting to do this for a long type. Why does this happen and how can I succ ...

Unable to modify the email and password fields within the user model

Having issues updating my user model in firebase. When trying to edit a user's password or email, the firebase storage remains unchanged while the firebase auth updates correctly. Check out my updateUser method below: private void updateUser() { ...

Exploring a JSON array with multiple dimensions

{ "response": [ { "address": { "features": { .......... }, "loc": { "latitude": 27.32423423423, "longitude": -84.0342423429 }, "blah1": "blah", "blah2": "blah", "stuff": { "stuff2": "stuff", "st ...

I am finding that my navbar is too lengthy on mobile due to the utilization of Bootstrap

I am encountering an issue with the code on my website . Everything is displaying correctly on my laptop, but when I view it on my mobile device, the navbar appears too long! If anyone could offer some assistance that would be greatly appreciated :) (I am ...

Using Javascript and CSS to Float DIV Elements

Recently, I've been working on a small algorithm that adds a special class to an element when the mouse reaches the halfway point or beyond on the X-axis of the browser. I also have a screenshot that demonstrates where this application will be utiliz ...

Overflowing is the width of Bootstrap's Grid Row

I managed to create this layout using only Bootstrap 5, without any CSS customization. Below is the HTML code I used: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name=&quo ...

Is the "Apply with LinkedIN" button not displaying correctly on the page?

I have managed to integrate the Apply with LinkedIN button on my website, but I am encountering a styling issue. The button is displaying strangely, even though I am using bootstrap 3.1. Has anyone else faced a similar problem and found a solution? I have ...

The alignment of columns in the fixed header table is off since it does not contain the necessary <thead> and <tbody> elements

On my page, I have three tables, with one of them containing a large amount of data. To make it easier to read, I decided to have a fixed header for the table. However, I am facing an issue where the columns in the thead (header) and tbody (body) are not a ...

I am dealing with a set of divs wrapped in a flex container that tend to overlap each other. Their heights vary and sometimes they wrap multiple times. Any suggestions on how to prevent this

I am encountering an issue where the width of the div remains the same after it has wrapped, causing overlapping. I want the first div to push the second to the right and so on. When I add a 100% width, it makes the width for the smallest div the same as ...

Acquiring Twitter updates for a dynamic Bootstrap carousel display

I've been trying to load multiple tweets from the stream into the slideshow, but I can only get one to show up. I believe it has to do with the placement of the <div id="feed"> element, but I can't seem to figure out what I'm missing. ...

Unlimited Possibilities in Designing Shared React Components

Seeking the most effective strategies for empowering developers to customize elements within my React shared component. For example, I have a dropdown and want developers to choose from predefined themes that allow them to define highlight color, font siz ...

How can we confirm with Selenium in Python that an empty HTML table does not contain any data?

After deleting all data from an HTML table on a webpage, I need to ensure that the table remains empty for testing purposes. What would be the most effective method to confirm this? One approach I am considering involves using Xpath as shown below: //tabl ...

The sticky navbar remains fixed only within the initial section of the page

Currently, I am working on a Bootstrap website that is supposed to be a one-page site with a navigation bar at the top. However, I am facing an issue where the navbar is sticky only for the first section and then disappears as I scroll down. How can I make ...