XPath返回错误的元素

时间:2018-05-10 11:15:03

标签: java xpath cucumber gherkin

我有一个问题,XPath在代码中返回错误的元素,但是当我把它放在我的浏览器和搜索元素与这样的xpath时按预期工作。

代码执行的路径返回下一个xpath的div。

例如xpath:

//div [@class="product justify-content-md-center"][1]/h2

返回第二个元素而不是第一个元素,但是当我将它粘贴到浏览器中时,它会获得正确的元素,因此我认为它不是xpath问题。我正在使用java的宁静黄瓜自动化。

我正在尝试从我的项目网站获取具有12个div产品目录的元素。这是带有PHP代码的html,列出了12个产品:

$num = $stmt->rowCount();
if ($num > 0) {
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
         extract($row);
         echo "<div class='product justify-content-md-center'>";
         echo "<img class='beerPicture' src='beers/{$picture}' style='height: 130px; width:130px'>";
         echo "<div class='click-callback'></div>";
         echo "<h2 class='header my-3 text-truncate'>{$name}</h2>";
         echo "<p class='description' style='display: none;'>{$description}</p>";
         echo "<p class='price'>{$price} lv.</p>";

         if ($quantity == 0) {
             echo "<h2 class='text_shadow'>Out of Stock</h2>";
         } else {
             $cartId = $row["id"];
             echo "<a class='btn' href='cartAction.php?action=addToCart&id=$cartId'>Add to cart</a>";
         }
             echo "<div class='quickview'>Description</div>";
             echo "</div>";
         }
    }
}

获取每个div的xpath的方法:

public String getProductName(int product) {
     String productName = getProduct().getWrappedElement().toString();
     String toRemove = productName.substring(0, 78);
     String result   = productName.replace(toRemove, "").replace("]/h2[text()]", "");

     String targetProductName = 
         result + "[" + product + "]" 
       + "/h2[@class=\"header my-3 text-truncate\" and text()]";

     System.out.println(targetProductName);
     System.out.println(getDriver().findElement(By.xpath(targetProductName)).getAttribute("textContent"));

     return getDriver().findElement(By.xpath(targetProductName)).getAttribute("textContent");
  }

我的小黄瓜情景:

Scenario Outline: I should be able to view description of any product
    Given I am logged in and on catalog page
    When I click on <any> product description button
    Then I should be shown the <any> product description
    Examples:
      |any|
      |1  |
      |2  |
      |3  |
      |4  |
      |5  |
      |6  |
      |7  |
      |8  |
      |9  |
      |10 |
      |11 |
      |12 |

0 个答案:

没有答案