尽管x路径选择了元素,并且我尝试使用java执行器,但在代码运行时,它只能单击购物车中第一个元素的更新按钮。下面是代码:
在将 3 个产品放入购物车后,我将文本框添加到列表中:
我已附上图片: 网址=“http://live.guru99.com/”
List<WebElement> li2 =driver.findElements(By.xpath(".//td[@class='product-
cart-actions']/input"));
for(int j=0;j<li2.size();j++)
{
if(j==0)
{
li2.get(j).clear();
li2.get(j).sendKeys("4");
driver.findElement(By.xpath(".//td[@class='product-cart-actions']/button[@title='Update']")).click();
li2 =driver.findElements(By.xpath(".//td[@class='product-cart-actions']/input"));
}
else if(j==1)
{
li2.get(j).clear();
li2.get(j).sendKeys("2");
//wait.until(ExpectedConditions.elementToBeClickable(By.xpath(".//td[@class='product-cart-actions']/button[@title='Update' and @type='submit']")));
//driver.findElement(By.xpath(".//td[@class='product-cart-actions']/button[@title='Update' and @type='submit']")).isDisplayed();
WebElement element = driver.findElement(By.xpath(".//td[@class='product-cart-actions']/button[@title='Update' and @type='submit']"));
try {
if (element.isEnabled() && element.isDisplayed()) {
System.out.println("Clicking on element with using java script click");
((JavascriptExecutor) driver).executeScript("arguments[0].click();", element);
} else {
System.out.println("Unable to click on element");
}
} catch (StaleElementReferenceException e) {
System.out.println("Element is not attached to the page document "+ e.getStackTrace());
} catch (NoSuchElementException e) {
System.out.println("Element was not found in DOM "+ e.getStackTrace());
} catch (Exception e) {
System.out.println("Unable to click on element "+ e.getStackTrace());
}
// if (element.isDisplayed()) {
// element.click();
//}
li2 =driver.findElements(By.xpath(".//td[@class='product-cart-actions']/input"));
}
else
{
li2.get(j).clear();
li2.get(j).sendKeys("3");
WebElement element1 = driver.findElement(By.xpath(".//td[@class='product-cart-actions']/button[@title='Update']"));
if (element1.isDisplayed()) {
element1.click();
}
}
最佳答案
这就是罪魁祸首:-
WebElement element = driver.findElement(By.xpath(".//td[@class='product-cart-actions']/button[@title='Update' and @type='submit']"));
因此,当您有多个具有相同定位器的元素时,WebDriver
单击第一个元素并继续前进。因此,如果您想单击 2nd
或 3rd
元素,您可以修改您的 xpath,例如:-
.//td[@class='product-cart-actions']/button[@title='Update' and @type='submit'][2] -- For 2nd Element
或者
.//td[@class='product-cart-actions']/button[@title='Update' and @type='submit'][3] -- For 3rd element.
但这不是一个好的方法,将来可能会有多个元素,并且您不会为每个元素添加索引。
最好的方法是引用产品名称
(在您的情况下唯一
)来识别更新
按钮。
关于java - 如何点击购物车页面中的更新按钮 - Url ="http://live.guru99.com/",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36968255/