如何通过Selenium Java将鼠标悬停在具有动态xpath的不同图像上

时间:2019-02-05 01:53:08

标签: java selenium selenium-webdriver mousehover webdriverwait

有七个图像。我想将鼠标悬停在每个图像上,然后检查是否显示AddToCart按钮。我尝试了以下代码,但无法正常工作。

参考:http://automationpractice.com/index.php

confint(pairs(emmeans(lmm, "Group"), type = "response"))
# contrast          odds.ratio        SE df lower.CL upper.CL
# Control / Patient   1.446683 0.1516588 91 1.174729 1.781595

Confidence level used: 0.95
Intervals are back-transformed from the log odds ratio scale

代码始终采用第一元素并打印alt属性文本。

2 个答案:

答案 0 :(得分:2)

请尝试一下,让我知道它是否有效。它对我有用。

List<WebElement> elmntimg=driver.findElements(By.xpath("//img[@class='replace-2x img-responsive']"));
            boolean res=false;

            for(int ix=0;ix<elmntimg.size();ix++)
            {
             Actions action=new Actions(driver);
             action.moveToElement(elmntimg.get(ix)).build().perform();
             System.out.println("Item By index"+elmntimg.get(ix).getAttribute("alt"));
             WebElement elecart=driver.findElement(By.xpath("//div[@class='button-container']/a[@title='Add to cart']"));
             if(elecart.isDisplayed())
                 res=true;
                 System.out.println("Element is available");


            }

答案 1 :(得分:0)

要将鼠标悬停在所有七(7)图像上,并检查是否显示文本为 AddToCart 的元素,您可以使用以下解决方案:

driver.get("http://automationpractice.com/index.php");
((JavascriptExecutor) driver).executeScript("return arguments[0].scrollIntoView(true);", new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[@class='homefeatured']"))));
List<WebElement> myProducts = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//ul[@id='homefeatured']//div[@class='product-image-container']/a/img")));
for(WebElement product:myProducts)
{
    new Actions(driver).moveToElement(product).build().perform();

    if(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//ul[@id='homefeatured']//div[@class='product-image-container']/a/img//following::a[@title='Add to cart']/span"))).isDisplayed())
        System.out.println("AddToCart button is displayed");
    else{
        System.out.println("AddToCart button is not displayed");
    }
}