5

In Selenium is it possible to identify the object by its type? e.g.

<input type="text" name="FirstName" value="">

Here can I identity the above element by its type of "text"?

  • Please do one question at a time. I also added code tagging as the code wasn't showing. – Michael Durrant Nov 5 '15 at 13:04
4

A slightly different interpretation of the question just in case :)

Lets say you have already located one or more elements in your test and you want to identify them by their 'type' html attribute...

// Lets locate the first found input tag
WebElement someElement = driver.findElement(By.cssSelector("input")); 

// And now lets store it's type
String typeOfElement = someElement.getAttribute("type"); 

Or if you want to deal with a list of elements

// Locate all input tags on the page
List<WebElement> someElements = driver.findElements(By.cssSelector("input")); 

// Now iterate through them and check for our desired match
for (WebElement anElement : someElements) {
    if (anElement.getAttribute("type").equals("text")) {
        // Do something
    }
}
10

Below are the answer to your questions.

In Selenium is it possible to identify the object by its type. Ex; Here do we able to identity above object by its type call text.

Yes, it is possible to identify the objects by its type. As already mentioned by @Michael Durrant, you can use the CssSelector for that.

driver.findElement(By.cssSelector("input[type='text']"));

Then do we able to count how may object were on the page where its type is text. Lets say some time page may contain more than one object which type is text. So I need the count in that case.

Yes, this too is possible using Selenium. You need to use the following code for that.

int i = driver.findElements(By.cssSelector("input[type='text']")).size(); //this will provide the number of elements with mentioned type
System.out.println(i);

Finally do we able to do separate action after identify those objects. Lest say i need to enter difference values into text fields.

This you can do in a multiple ways:

Solution 1: Using the index of the elements. Once you know the number of elements you can set different value of each element using their index position e.g.

driver.findElements(By.cssSelector("input[type='text']")).get(1).sendKeys("Name");

Remember, index of elements will start from '0', so if there are 4 elements on your page; then their indexes will be 0, 1, 2, 3

Solution 2: Store your elements to a Array list and then set value of these list elements. You can use CSV/Excel or any other external file too for setting value of these list elements.

driver.findElements(By.cssSelector("input[type='text']")).toArray();
0

You can identiy a page element like that with a css selector

input[type='text']

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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