我试图自动化以下方案:
- 转到Amazon.com
- 搜索耳机
- 在第一个结果页面中添加所有畅销书
我遵循的步骤脚本为此:
- 转到Amazon.com
- 在搜索字段中输入文本"耳机"
- 单击搜索按钮
- 单击标记为"畅销书"的链接
- 单击"添加到购物车"按钮
- 导航返回结果页
- 单击另一个标记为"畅销书"的链接
- 单击"添加到购物车"按钮
- 导航返回结果页
所有畅销书都有相同的XPath:
//span[.='Best Seller']/../../../../../../../../following-sibling::div/div/following-sibling::div/div/div/div/div/div/h2/a/span
因此,我已经实现了一个网络列表,如下所示:
List<WebElement> bestsellers = driver.findElements(By.xpath("xpath of bestsellers"));
我已经在链接上实现了单击,并使用循环以3种方式添加到购物车中:
for(WebElement product: bestsellers) {
product.click();
clickOnAddToCartButton();
driver.navigate().back();
}
for(int i=0; i<bestsellers.size(); i++) {
System.out.println(bestsellers.size());
bestsellers.get(i).click();
clickOnAddToCartButton();
driver.navigate().back();
}
Iterator<WebElement> i = bestsellers.iterator();
while(i.hasNext()) {
WebElement product = i.next();
wait.until(ExpectedConditions.elementToBeClickable(product));
product.click();
clickOnAddToCartButton();
driver.navigate().back();
}
我运行脚本时列表中有3个元素。执行循环后,第一个元素被单击并添加到购物车中,驱动程序将导航回结果页面。然后,我使用上述3种方法获得了StaleelementReferenceException。
更新:我已经实施了如下的方案:
for(int i=0; i<bestsellers.size(); i++) {
System.out.println("Current :" + i);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath(".//span[.='Best Seller']/../../../../../../../../following-sibling::div/div/following-sibling::div/div/div/div/div/div/h2/a/span")));
driver.findElements(By.xpath(".//span[.='Best Seller']/../../../../../../../../following-sibling::div/div/following-sibling::div/div/div/div/div/div/h2/a/span")).get(i).click();
clickOnAddToCartButton();
//clickOnViewCart();
try {
wait.until(ExpectedConditions.elementToBeClickable(cartButton));
}catch(TimeoutException e) {
wait.until(ExpectedConditions.elementToBeClickable(viewCartButton));
}
if(i==(bestsellers.size()-1)) {
try {
wait.until(ExpectedConditions.elementToBeClickable(cartButton));
cartButton.click();
break;
}catch(TimeoutException e) {
wait.until(ExpectedConditions.elementToBeClickable(viewCartButton));
viewCartButton.click();
break;
}
}
driver.navigate().back();
您单击浏览器中的元素或back((的那一刻,元素引用将在硒中进行更新,因此您无法指向带有旧引用的元素,并且导致了该元素StatleElementException
。
当您必须通过多个元素相互作用进行迭代时,请考虑这种方法。
List<WebElement> bestsellers = driver.findElements(By.xpath("xpath of bestsellers"));
for(int i=0; i<bestsellers.size(); i++) {
System.out.println("Current Seller " + i);
// here you are getting the elements each time you iterate, which will get the
// latest element references
driver.findElements(By.xpath("xpath of bestsellers")).get(i).click();
clickOnAddToCartButton();
driver.navigate().back();
}