Brian
Brian

Reputation: 467

Interacting with Webdriver elements from a list

It's late and I must be missing something simple here but I just can't figure it out.

I am attempting to automate the user input of a form using Webdriver. The catch is that the form is dynamic and has lots of custom fields. In this case, I am trying to send a simple string to ALL of the text entry boxes on the form. I think I'm half way there; I am able to pull all text fields using XPath and put them into a List. However, I'm not sure how to interact with them once they are there.. Here is the code I have so far:

List<IWebElement> textfields = new List<IWebElement>();

var test = Driver.FindElements(By.XPath("//*[@type='text']"));

foreach (IWebElement fields in test)
{
    textfields.Add(fields);
}

The way in which I interact with WebDriver is something like this:

Driver.FindElements(By.XPath(querygoeshere)).SendKeys("test");.

However, everything in the list is an IWebElement.. What do I do next? Am I on the wrong path here?

Upvotes: 1

Views: 11604

Answers (2)

Arran
Arran

Reputation: 25076

Note that your current XPath query is not actually going to select all text boxes. It will only select elements that have a type of text - which can only be inputs.

This will miss out textarea elements. This may be OK for you, but nonetheless:

var textBoxes = new List<IWebElement>();
textBoxes = Driver.FindElements(By.CssSelector("input[type='text']"));

foreach (IWebElement textBox in textBoxes)
{
    textBox.SendKeys("test");
}   

To include textarea elements:

var textBoxes = new List<IWebElement>();
var textAreas = new List<IWebElement>();

textBoxes = Driver.FindElements(By.CssSelector("input[type='text']"));
textAreas = Driver.FindElements(By.CssSelector("textarea"));

textBoxes.AddRange(textAreas);

foreach (IWebElement textBox in textBoxes)
{
    textBox.SendKeys("test");
}   

At the very least, if you must use XPath, then be explicit - the * will search all elements, you only want input elements anyway - so make it //input[@type='text'].

Upvotes: 1

zodvik
zodvik

Reputation: 921

I am not sure of the C# syntax, but an approach like this should be helpful:

List<IWebElement> textfields = new List<IWebElement>();
textfields = Driver.FindElements(By.XPath("//*[@type='text']"));

foreach (IWebElement field in textfields){
    field.SendKeys("test);
}

Upvotes: 2

Related Questions