0

I've several page elements / records having xpath / id's like this

//*[@id='xyz-model-car-card-0']/car
//*[@id='xyz-model-car-card-1']/car
//*[@id='xyz-model-car-card-2']/car

and i am looking to add these webelements using List so that i can take any action on them.

List<WebElement> item = Arrays.asList();
// incase i want to navigate to 5 cards..
for(int i=0;i<5;i++) {
item.add(By.id('xyz-model-car-card-'+i));
}

but, i am unable to add it.. giving below error..

*add (org.openqa.selenium.WebElement)
in List cannot be applied to (org.openqa.selenium.By)*

Whats the best way to deal with such webelements name if we want to load them in one go.enter code here

Pl. share some example.. Thanks in advance!

2 Answers 2

3

Assuming a webdriver named 'driver':

List<WebElement> xyzModels = driver.findElements(By.xpath("//*[starts-with(@id='xyz-model-car-card-')]/car));

For (WebElement car : xyzModels) {
    //your code here...
}
Sign up to request clarification or add additional context in comments.

Comments

1

You are trying to add the By object to your WebElement list:

item.add(By.id('xyz-model-car-card-'+i));

You need to add the web element instead (assuming you are using driver when you instantiate your new browser object):

item.add(driver.findElement(By.id('xyz-model-car-card-'+i)));

But, I agree with Bill Hileman's answer. Best way to add the elements to a list is to do this:

List<WebElement> myList = driver.findElements(By.....)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.