3

I have multiple input HTML tags on same page having same id and name or class,

Now How should I find 2nd or 3rd.. etc input. I can work with arrays so Do we have some function which will return all the textBox(input tag) from that page.

Mudit Singh
  • 185
  • 1
  • 1
  • 11

4 Answers4

8

First you create a list with FindElements, then you can iterate through that list. For example:

var allTextBoxes = driver.FindElements(By.TagName("input"));

foreach(var textBox in allTextBoxes)
{
    textBox.DoSomething();
}

You can use a for-loop as well:

for(int i = 0; i < allTextBoxes.Count; i++)
{
   allTextBoxes[i].DoSomething();
}     

Or if you want a specific Element, in example the 3rd:

allTextBoxes[2].DoSomething();
Anaxi
  • 316
  • 1
  • 7
3

Expanding on Anaxi's answer,

If you are using the PageObject framework you can do it like this and set the FindsBy attribute on a property:

[FindsBy(How = How.Id, Using = "YourId")]
public IList<IWebElement> ListOfWebElements { get; set; }
Jamie Rees
  • 7,973
  • 2
  • 45
  • 83
0

i dont know about selenium... but to select element of html page you can use HtmlAgilityPack..

HtmlWeb hw = new HtmlWeb();
HtmlDocument doc = hw.Load(@"http://example.com");
HtmlNode node = doc.DocumentNode.SelectNodes("//div[@class='your_class_name']");

it will return a list of node that contains your_class_name.. then find and use the one you want.

to select all the input tags from that page you can use

foreach (var input in doc.DocumentNode.SelectNodes("//input"))
{
    //your logic here 
}

hope it helps..

Sadid Khan
  • 1,836
  • 20
  • 35
  • 1
    Good answer but I would not recommend mixing HtmlAgilityPack and Selenium, it would just get confusing for beginners. – Jamie Rees May 05 '15 at 09:08
0

In C# I use FindElements then ElementAt():

var foo= Driver.FindElements(By.XPath("//div[@class='your_class_name']"));
var foo2= foo.ElementAt(1);

If it's 10 elements with the same ID (which is HORRIBLE) and I'd like to grab the 8th element, I just use ElementAt(8); (or index 7 or however you're set up).

It's a tough call. I'd much rather have them fix the code but in some cases that's just not going to happen... at least not in the near future.

Hope this helps.

icebat
  • 4,696
  • 4
  • 22
  • 36
Deez
  • 11
  • 4