无法使用selenium webdriver单击/鼠标悬停在元素上

时间:2013-11-18 07:26:47

标签: java selenium webdriver

1.转到此网址: - > http://wallethub.com/profile/test_insurance_company/

2.在页面的右侧,将鼠标悬停在星星上,然后点击第五颗星 代码应该实际上(1)做悬停和(2)当你将鼠标悬停在它们上面时确保内部的星星点亮,然后(3)点击第五颗星。

以下不起作用

 import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
import org.openqa.selenium.interactions.Actions;

public class Wallethub2 {

    /**
     * @param args
     */
    public static void main(String[] args) {

        ProfilesIni prof = new ProfilesIni();
        FirefoxProfile fp = prof.getProfile("sel");

        WebDriver driver=new FirefoxDriver(fp);

        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        driver.get("http://wallethub.com/profile/test_insurance_company/");

//      Xpaths of 5 stars
       String star1="//div[@class='wh-rating-choices-holder']/a[contains(@href, '#')][1]";
       String star2="//div[@class='wh-rating-choices-holder']/a[contains(@href, '#')][2]";
       String star3="//div[@class='wh-rating-choices-holder']/a[contains(@href, '#')][3]";
       String star4="//div[@class='wh-rating-choices-holder']/a[contains(@href, '#')][4]";
       String star5="//div[@class='wh-rating-choices-holder']/a[contains(@href, '#')][5]";

        WebElement srating1=driver.findElement(By.xpath(star1));            
        WebElement srating2=driver.findElement(By.xpath(star2));            
        WebElement srating3=driver.findElement(By.xpath(star3));            
        WebElement srating4=driver.findElement(By.xpath(star4));            
        WebElement srating5=driver.findElement(By.xpath(star5));    


        Actions builder = new Actions(driver);  
                builder.moveToElement(srating1).build().perform();
        builder.moveToElement(srating1).build().perform();
        builder.moveToElement(srating2).build().perform();
        srating3.click();








    }

}

1 个答案:

答案 0 :(得分:5)

如果您想点击第五颗星,请srating5.click()

如果您的代码出现问题,请尝试使用:

Locatable hoverItem = (Locatable) driver.findElement(srating1);

Mouse mouse = ((HasInputDevices) driver).getMouse();

mouse.mouseMove(hoverItem.getCoordinates());

为第一颗星做悬停然后重复。

对于最后一项,您应该能够做您正在做的事情或尝试

Locatable clickItem = (Locatable)driver.findElement(srating3).getLocation();
clickItem.getCordinates(clickItem).click();