16

I am using Selenium to test a website, does this work if I find and element by more than one criteria? for example :

 driverChrome.findElements(By.tagName("input").id("id_Start"));

or

driverChrome.findElements(By.tagName("input").id("id_Start").className("blabla"));

4 Answers4

16

No it does not. You cannot concatenate/add selectors like that. This is not valid anyway. However, you can write the selectors such a way that will cover all the scenarios and use that with findElements()

By byXpath = By.xpath("//input[(@id='id_Start') and (@class = 'blabla')]")
List<WebElement> elements = driver.findElements(byXpath);

This should return you a list of elements with input tags having class name blabla and having id id_Start

Community
  • 1
  • 1
Saifur
  • 16,081
  • 6
  • 49
  • 73
14

To combine By statements, use ByChained:

driverChrome.findElements(
    new ByChained(
        By.tagName("input"),
        By.id("id_Start"),
        By.className("blabla")
    )
)

However if the criteria refer to the same element, see @Saifur's answer.

user3335966
  • 2,673
  • 4
  • 30
  • 33
George
  • 180
  • 2
  • 9
  • How is this not the accepted answer? If the tag, ID, and class all refer to the same element, then this does allow one to use multiple selectors. I prefer this over using an XPath (or something similar) since it's more concise and clearly describes the element I'm looking for. – coolDude Sep 07 '21 at 22:08
2

CSS Selectors would be perfect in this scenario.

Your example would

By.css("input#id_start.blabla")

There are lots of information if you search for CSS selectors. Also, when dealing with classes, CSS is easier than XPath because Xpath treats class as a literal string, where as CSS treats it as a space delimited collection

Robbie Wareham
  • 3,380
  • 1
  • 20
  • 38
0

Based @George's repply, the same code for C# :

//reference
using OpenQA.Selenium.Support.PageObjects;

...

int allElements = _driver.FindElements(new ByChained(
                    By.CssSelector(".sc-pAyMl.cnszJw"),
                    By.Id("base-field")
                    )).Count();
Diego Montania
  • 322
  • 5
  • 12