如何在 java selenium 中使用循环从项目网格中找到相同的元素?

How to find same element from item grid using loop in java selenium?

我正在尝试查找添加到购物车的按钮存在或不使用来自以下代码的所有项目框的循环

<div class="page-body">
<div class="product-selectors">
<div class="product-filters-wrapper">
<div class="product-grid">
<div class="item-box">
<div class="item-box">
<div class="item-box">
<div class="item-box">
</div>

在代码后的每个项目框中

<div class="item-box">
<div class="product-item" data-productid="20">
<div class="picture">
<div class="details">
   <h2 class="product-title">
   <div class="product-rating-box" title="1 review(s)">
      <div class="description"> 12x optical zoom; SuperRange Optical Image Stabilizer </div>
      <div class="add-info">
         <div class="prices">
            <div class="buttons">
               <input class="button-2 product-box-add-to-cart-button" type="button" onclick="AjaxCart.addproducttocart_catalog('/addproducttocart/catalog/20/1/1 ');return false;" value="Add to cart">
            </div>
         </div>
      </div>
   </div>
</div>

我需要使用循环找到所有项目框是否存在添加到购物车按钮。如果有人可以帮忙

我建议如果没有必要就避免循环。除非有明确的需要,否则您不需要执行循环来找出答案。您可以找到 添加到购物车按钮 的计数并与已知值

进行比较
By byCss = By.cssSelector(".item-box>div input[value='Add to cart']");
int cartCount = driver.findElements(byCss).size();

if (cartCount != 4){
    //fail the test
}

如果你恰好循环检查输入按钮是否存在。

By itemBoxes = By.className("item-box");
By button = By.cssSelector("[type='button'][value='Add to cart']");

List<WebElement> webElementList = driver.findElements(itemBoxes);
for (WebElement element: webElementList){
    //simply taking size if exist it will return 1
    if (element.findElements(button).size() != 1){
        //fail
    }
}

您可以在循环内使用 xpath 搜索。

类似于

".//input[@value='Add to cart'][1]"
".//input[@value='Add to cart'][2]"
".//input[@value='Add to cart'][3]"
etc

不确定这个 xpath 是否正确,但通常它对你有用,兄弟。 或者像这样:

string xpath=".//input[@value='Add to cart']";

var AddToCartBtnsList = driver.findElements(By.Xpath(xpath));

foreach(IWebElement button in AddToCartBtnsList )
{
    button.click();
}