I have a method in which I am trying to add 12 web elements:
private List<WebElement> iphoneSnippetList = new ArrayList<>();
@Test
public void test(){
chromeDriver.get("https://market.yandex.ru/catalog--smartfony/54726/list?hid=91491&glfilter=7893318:153043&onstock=1&local-offers-first=0");
new WebDriverWait(chromeDriver, 15).until(ExpectedConditions.elementToBeClickable(By.xpath("//article[@data-autotest-id='product-snippet'][1]")));
for (int i = 0; i <= 12; i ) {
iphoneSnippetList.add((WebElement) By.xpath("//article[@data-autotest-id='product-snippet'][" i "]"));
}
System.out.println(iphoneSnippetList);
}
Simplified DOM elements in which I only need to get the text :
<article class="_2vCnw cia-vs cia-cs" data-autotest-id="product-snippet"</article>
<article class="_2vCnw cia-vs cia-cs" data-autotest-id="product-snippet"</article>
<article class="_2vCnw cia-vs cia-cs" data-autotest-id="product-snippet"</article>
I need to add all 12 web elements to my array and then make sure that the received elements contain the name "Iphone", but when adding elements, there is exception:
java.lang.ClassCastException: class org.openqa.selenium.By$ByXPath cannot be cast to class org.openqa.selenium.WebElement (org.openqa.selenium.By$ByXPath and org.openqa.selenium.WebElement are in unnamed module of loader 'app')
CodePudding user response:
iphoneSnippetList
is a List of WebElement
in Java-Selenium bindings.
I am not sure why you want to add 12 web elements using the loop, instead a findElements
with right xpath
would have been a good choice. Anyway, there's a problem with you code related to casting.
See below, driver.findElement
will return the web element
, and we are storing that into a variable called Webelement e
, and adding the same into iphoneSnippetList
for (int i = 0; i <= 12; i ) {
WebElement e = driver.findElement(By.xpath("//article[@data-autotest-id='product-snippet'][" i "]"));
iphoneSnippetList.add(e);
}
System.out.println(iphoneSnippetList);
Also, this loop will run for 13 times not 12 times. In case you want this to run for 12 times, initialize i = 1
not i = 0
I think you will have issue with xpath also, cause you are not using xpath
indexing
correctly.
try this instead :
for (int i = 1; i <= 12; i ) {
WebElement e = driver.findElement(By.xpath("(//article[@data-autotest-id='product-snippet'])['" i "']"));
iphoneSnippetList.add(e);
}
System.out.println(iphoneSnippetList);