How to use OR Condition in selenium findElements()

2019-04-28 20:20发布

问题:

I want to get all WebElement information having class name "act" or "dact"

I am using below line of code to get all class information for "act". Can any one help me to use OR condition in class name?

List<WebElement> nL2 = driver.findElements(By.className("act"));

Something similar to this; so that I don't have to write two separate line for each class.

//this is not working

List<WebElement> nL2 = driver.findElements(By.className("act | dact"));

Thanks!

回答1:

Can you just combine the two lists?

List<WebElement> act = driver.findElements(By.className("act"));
List<WebElement> dact = driver.findElements(By.className("dact"));
List<WebElement> all = new ArrayList<WebElement>();
all.addAll(act);
all.addAll(dact);

Alternatively, you could use an xpath locator as suggested by @Alejandro

List<WebElement> all = driver.findElements(By.xpath("//*[@class='act' or @class='dact']"));


回答2:

I know this question is really old but probably the easiest way to do this is to use a CSS selector like

driver.findElements(By.cssSelector(".act, .dact"));

You should prefer CSS selectors to XPath because the browser support is better and they are more performant (and I think they are easier to learn/understand). CSS selectors can do everything By.className() can plus a whole lot more. They are very powerful and very useful.

Some CSS selector references to get you started.

W3C CSS Selector Reference

Sauce Labs CSS Selector Tips