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.

up vote 4 down vote accepted

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();
  • I am using allTextBoxes[2].sendKeys("someTest").... But this is not working. – Mudit Singh May 8 '15 at 10:58

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.

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; }

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..

  • 1
    Good answer but I would not recommend mixing HtmlAgilityPack and Selenium, it would just get confusing for beginners. – Jamie Rees May 5 '15 at 9:08

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.