Selenium getattribute list c#

Asked

Viewed 1,019 times

-1

I’m having a problem creating a list with attributes follows HTML code:

 <div class="post  clearfix" data-post-id="92842173">...</div>
 <div class="post  clearfix" data-post-id="92841636">...</div>
 <div class="post  clearfix" data-post-id="92618462">...</div>
 <div class="post  clearfix" data-post-id="90658834">...</div>

current c# code:

var valor = chromeDriver.FindElement(By.XPath("//div[contains(@class, 'post')]")).GetAttribute("data-post-id"); 

so just get the first one data-post-id="92842173".

I would like to create a list of all data-post-id. I have tried to do as follows below, but it is a mistake.

List <IWebElement> list1  = chromeDriver.FindElement(By.XPath("//div[contains(@class, 'post')]")).GetAttribute("data-post-id"); 
  • chromeDriver does not have a Findelements method?

  • yes, it has, I use to locate the div where it contains the attribute I need to extract, but I can’t extract all or 1 by 1, I can only extract the 1° attribute, I need a function to extract all the post-id data.

  • See if you have something like Findallelement or selectElement on your chromeDriver

1 answer

0

Come on, let’s go, there is a method in the Selenium to be able to pick up more than one element using the same reference, in this case the path you used to find the first:

By.XPath("//div[contains(@class, 'post')]");

Instead of using

List <IWebElement> list1  = chromeDriver.FindElement(By.XPath("//div[contains(@class, 'post')]"))

you will use

IList<IWebElement> list1 = chromeDriver.FindElements(By.XPath("//div[contains(@class, 'post')]"));

Ready, now that you have a list with all these IWebElement, to extract the data-post-id of each, let’s assume that you want to store them in one List, then stay like this:

List<string> dataPost = new List<string>();

for(int i = 0; i < list1.Count(); i++){
    dataPost.Add(list1[i].GetAttribute("data-post-id"));
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.