A guide on how to iterate through elements with a designated class name using Selenium in JavaScript

I have encountered a challenge with looping through multiple div containers on the page that all have the same class name 'sponge'. My goal is to retrieve details from each of these containers, but I am struggling to figure out the right approach. Here is my current attempt...

const containers = await driver.findElements(By.className(`sponge`))

for(let i = 0; i < containers.length; i++){
  let details = await containers[i].findElement(By.xpath(`//div[2]/div[1]/div/p`)).getText()
  console.log(details)
}

Unfortunately, when I run the code snippet above, it retrieves the same 'details' from the first 'sponge' container repeatedly for the total number of 'containers'. It seems to be unable to locate the specific 'details' in each individual container as intended.

Answer №1

If you want to access the direct child element of a parent element, you can do so by using .. Give it a try now.

const elements = await driver.findElements(By.className("sponge"))

for(let i = 0; i < elements.length; i++){
  let result = await elements[i].findElement(By.xpath(".//div[2]/div[1]/div/p")).getText()
  console.log(result)
}

Answer №2

  • If you're looking to scrape this website, I recommend considering alternative methods such as using modules like request, got, axios, node-fetch. These modules can send an HTTP request to the page and retrieve the HTML content for further processing. You can then utilize a module like jquery-jsdom to access the DOM elements of the response and extract the desired information using jQuery selectors.
  • When extracting data through scraping, utilizing HTTP requests can be more effective.

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

Using the outer ng-repeat's object property to filter nested ng-repeat items

I'm currently working on nesting two ng-repeats with two separate JSON files. The goal is to filter the second ng-repeat based on parameters from the first ng-repeat. The first JSON file, $scope.matches, includes information about each match in the W ...

Setting a Value?

Within the services.js/Cordova file, I am encountering an issue with the following code: .factory('GCs', ['$http', function($http) { var obj= {}; $http.post("mydomina.com?myrequest=getbyid", { "id": "1"} ) ...

Is there a more efficient method for streamlining the Express-Validator middleware in a separate file

In my current project, there is a lot of validation required using Express-Validator. In each file, I find myself repeating the same validation code: //Validation and Sanitizing Rules const validationRules = [ param('tab').isString().isLength({ ...

What is the best way to incorporate alternating classes into a dynamic feed of thumbnail images?

I am integrating a YouTube user's video channel feed onto a webpage using two plugins called jYoutube and jGFeed. If you are interested in the plugins I mentioned, here they are: jGFeed: jYoutube: However, I have encountered an issue with the im ...

What issues can be identified in this ajax.js script?

This particular function is designed to verify the existence or availability of a user login, yet even when the user database table is empty, the form consistently indicates that there is a duplicate entry. As a result, the submit button disappears. What c ...

To enable Android permissions while testing with BrowserStack Automate using Selenium and Appium, simply click on the permission prompts

We are currently developing an automated test suite using BrowserStack Automate for our tests in Selenium with Appium. One particular test requires us to play DRM protected content which works fine on desktop platforms, but we are facing challenges testin ...

How to handle redirects based on status codes in AngularJS $http requests

My angular application includes numerous $http requests, and I am looking for a way to automatically redirect users to the login page in case the server session expires (resulting in a 401 error). Does anyone have a solution that can handle this for all ...

Header Blocks that are Fixed While Scrolling in fullPage.js Sections Using the "scrollOverflow: true" Feature

I am experiencing an issue where a fixed header on my website prevents scrolling through sections when hovering, specifically when the setting scrollOverflow: true is enabled. However, everything works fine and scrolling through all sections is possible w ...

Remove a row from X-editable after confirming (AngularJS)

I recently added a confirmation feature to the delete button, but I'm facing an issue where the row is not getting removed even though the code seems to be working fine. HTML <button class="btn btn-danger" confirmed-click="removeUser($index)" ng- ...

How can you transfer data from a jQuery function to a designated div element?

I'm struggling to transfer data from a function to a specific div, but I can't seem to make it work. I'm in the process of creating a gallery viewer and all I want is to pass the counter variable, which I use to display images, and the total ...

The behavior of CSS position: sticky varies depending on whether the user is scrolling up or scrolling down

I am experiencing an issue in my Vue CLI app where a component with the position: sticky CSS property is being partially hidden under the top of the browser when scrolling down, but works correctly when scrolling up. This behavior is also observed on my Ga ...

What is the best method for communicating between windows in an electron application?

As I embark on the journey of creating my first electron app, I kindly ask for your understanding :) Upon clicking a button in the main Window, a new window should open displaying a JSON string. This action is captured by ipcMain: ipcMain.on("JSON:ShowPa ...

The function fails to trigger the ajax request upon clicking the button

Below is a button that I need to work with: <a class="action submit btn btn-danger btn-lg pull-right" onclick="return finishExam();"><i class="glyphicon glyphicon-stop"></i> Finish Exam</a> Here's the JavaScript function asso ...

What is the best way to create an XPath that can target specific data in an HTML table column that might change its position?

List<WebElement> brandNames = driver.findElements(By.xpath("//tbody/tr/td[1]")); I am attempting to create an xpath for "Brand Name" that will capture all the values under the "Brand Name". Each time I refresh, the "Brand Name" moves to an ...

If the final page is reached, the Python Selenium Script will proceed without waiting indefinitely

I have a script that successfully clicks through all the next pages on this website until it reaches the last page. However, once it reaches the last page, it waits indefinitely. How can I modify the script to continue executing the rest of the code once ...

Is there a way to retrieve the name of a JSON or obtain the file path using NodeJS Express Router?

I've been experimenting with adding a named routers feature to the Express router for my NodeJS project. I managed to implement it successfully, but there's one thing I'm stuck on... the path. Specifically, when I have a route setup like thi ...

Getting real-time comments after they have been submitted in ReactJS

Is it possible to dynamically display newly added comments in real-time without refreshing the page after submitting them to the database through an API? Here's a snippet of the code I currently have: const PostWidget = ({ post }) => { ...

Having trouble adding the selenium ide extension to webdriver

I'm having trouble figuring out why the code snippet provided below isn't adding an extension properly. Any suggestions? FirefoxProfile profile1 = new FirefoxProfile(); profile1.AddExtension(@"C:\\Downloads\\selenium-ide-2.5. ...

Using Selenium with Python, input text into a field by sending keys

I am facing an issue with sending a string to the textfield on a webpage. Every time I open the page, the xpath changes, so I attempted to use class name or tag name instead. Unfortunately, I keep getting an error indicating that keys cannot be passed to t ...

Arrow function returns itself, not the function

While working with React, I've been using utility functions for managing API calls. I noticed that when the arrow function is no longer anonymous, it successfully returns a pending promise – which is exactly what I want. However, if the arrow functi ...