Problem with locating elements using Selenium xpath

While using selenium and xpath, I encountered a peculiar issue. On a page, there are 25 <a> tags with nested <img/> tags. I am trying to retrieve all these elements using the findElements() method. Interestingly, upon inspecting the page source and searching for the substring "alt="Expand List"", I find 25 instances. However, when I run the command

let items = await driver.findElements(By.xpath("//a[//img[contains(@alt,'Expand List')]]"))
, it returns 32 items. Upon further investigation in Google Chrome's console, I noticed that some <a> contain images with different alt values. Any insights on this issue? Here is the piece of code I used:

    let text = await driver.getPageSource();
    var count = (text.match(/alt="Expand List"/g) || []).length;
    let items = await driver.findElements(By.xpath("//a[//img[contains(@alt,'Expand List')]]"))
    console.log(count, items.length); //outputs 25, 32

An image with the alt attribute Collapse List is also present within an <a> tag:

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

Similarly, another image with the alt attribute Collapse List appears within an <a> tag:

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

Answer №1

Make sure your xpath is similar to this:

//a/img[contains(@alt,'Expand List')]

A single slash shows that it's a child of the parent //a.

I suggest using a browser extension to test xpaths. One that I find very useful is ChroPath. You can also try testing xpaths in the devtools console like this:

$x('//a/img[contains(@alt,'Expand List')]')

This will produce an output like this:

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

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

Ways to make a component gradually appear and disappear in an Angular application

I have developed a task management application using Angular and I wanted to implement a fading effect for each task when it is created and before it is deleted. Despite successfully applying the fade in effect at the todo-item component level, I encounter ...

The process of executing a PHP file from JavaScript using XMLHttpRequest is experiencing issues on a XAMPP local server

I'm attempting to execute a PHP file using JavaScript. I have my XAMPP server set up and all files saved in the htdocs folder. The PHP file is also stored in the htdocs folder and works correctly when accessed via http://localhost/php_test.php in Chro ...

Show a variety of pictures using React

Is it possible to repeat an image (e.g. photo.jpg) n times in Reactjs using a provided value for n in props? If yes, how can this be achieved? function Card(props) { for (let i = 0; i < props.rating; i++) { <img className="star" src ...

JavaScript - Executing the change event multiple times

Below is the table I am working with: <table class="table invoice-items-table"> <thead> <tr> <th>Item</th> <th>Quantity</th> <th>Price</th> & ...

Issues with displaying images in Fancybox

I've integrated FancyBox into my website, but I'm experiencing a minor issue. While the FancyBox works perfectly in Dreamweaver, it seems to malfunction in various browsers. As someone who is not well-versed in programming, I'm struggling t ...

Using AngularJS Typeahead with restrictions on $http requests

I have been attempting to restrict the number of results displayed by Angular Bootstrap Typeahead during Async calls, but unfortunately, it does not seem to be functioning as expected. <input type="text" ng-model="asyncSelected" placeholder="Locations ...

What is the best approach to streamline and optimize this JavaScript logic code for greater efficiency?

Working on a project, I find myself dealing with 21 buttons that can be in either an active or inactive state. The state of certain buttons is influenced by the press of other buttons as well as their own activation. To handle this in my HTML, I utilize ng ...

Is the webdriver downloading the temporary file instead of the CSV document?

I've developed a script that searches for companies on the violationtracker.goodjobsfirst.org website and automatically downloads the CSV file with company details. You can view an example of this for Nike here. Initially, the code was running smooth ...

Grab the URL from React Router

I need assistance with writing a function that updates the current location to match the route of a clicked button. Currently, the code is returning the URL of the page where the button was clicked, not the path related to the button itself. Are there an ...

Tips for locating the highest number in JavaScript

I'm having trouble with my code where the first number, even if it's the largest, is not displaying as such. Instead, it shows the second largest number. Even when following suggestions, I encountered an issue where if the numbers are entered as ...

Changing the caret position in a contenteditable div using HTML React

In a recent project I worked on, I included contenteditable divs. Whenever the enter key is pressed within one of these divs, it splits into two separate contenteditable divs. However, after React re-renders the components, the caret tends to go to the beg ...

Cross-Origin Resource Sharing Problem - Angular version 8 with NodeJS and ExpressJS

I've attempted various solutions from different sources and have a feeling that I may be overlooking something minor here. In my setup, I have an AngularJS 8 application running on Node 10 with ExpressJS. The specific issue I'm encountering rela ...

Executing multiple HTTP requests simultaneously in groups using an asynchronous for loop for each individual request

I'm currently working on running multiple requests simultaneously in batches to an API using an array of keywords. Read Denis Fatkhudinov's article for more insights. The issue I'm facing involves rerunning the request for each keyword with ...

Error: Watir WebDriver File Detection Issue

I am facing an issue with uploading files through a file field form. While it works fine locally, I am encountering difficulties when trying to upload files to a remote machine using Selenium Grid tests. The solution involves using a file detector, which ...

Exploring an unusual HTML structure using Python's Beautiful Soup and urllib for web scraping

While extracting data may not be a challenge, the real issue lies in locating it. My focus is on scraping football data from a website that presents statistics either for all years or for specific seasons. However, despite selecting a particular season, ...

Encountering a problem when using the wait method in Selenium to loop through a list of participants

While troubleshooting the program, I noticed that all three participants are selected during debugging. However, when I run the program, an error is thrown for the second participant: java.lang.IllegalStateException: The Network Member can not be found T ...

After stopping the interval with clearInterval(), you can then use the res.send method

I need to continuously log the current date and time to the server console then stop logging after a specified time, returning the final date and time to the user. How do I properly utilize ClearInterval() in this scenario? const express = require(" ...

Navigating through frames in Selenium can be a bit tricky,

I am having trouble logging into this website. Upon loading the page, a frame appears. I have attempted to switch to the frame without success. public void logon(String Username,String Password,String trns) { Configuration.driver.get(Configuration.U ...

Selecting Content Dynamically with jQuery

I have a webpage with multiple dynamic content sections. <div id="content-1"> <div id="subcontent-1"></div> <i id="delete-1"></i> </div> . . . <div id="content-10"> <div id="subcontent-10"></d ...

I'm experiencing an issue where my JavaScript function is only being triggered

I have a simple wizard sequence that I designed. Upon selecting an option from a dropdown menu on the first page, a new page is loaded using jQuery ajax. However, when clicking back to return to the original page, my modelSelect() function, responsible for ...