Actions 类 - click(WebElement ele) 函数不单击

Aka*_*gam 4 selenium selenium-webdriver

我正在尝试使用Actions 类的click(WebElement)方法来单击 google 主页上的元素。代码运行成功,但是没有触发点击事件。

package p1;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.WebElement;



public class ClickLink 
{
    static WebDriver driver;
    public static void main(String[] args)
    {
        try
        {
        driver = new FirefoxDriver();
        driver.manage().window().maximize();
        driver.get("http://www.google.com/");
        WebElement icon = driver.findElement(By.xpath(".//*[@id='gbwa']/div[1]/a"));
        Actions ob = new Actions(driver);
        ob.click(icon);
        System.out.println("Link Clicked !!");
        Thread.sleep(10000);
        driver.close();
        }
        catch(Exception e)
        {
            System.out.println("Exception occurred : "+e);
            driver.close();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是执行上述脚本时的结果:[链接]

但是,当使用 WebElement 接口的 click() 方法单击同一元素时,就会触发单击。

package p1;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.WebElement;

public class ClickLink 
{
    static WebDriver driver;
    public static void main(String[] args)
    {
        try
        {
        driver = new FirefoxDriver();
        driver.manage().window().maximize();
        driver.get("http://www.google.com/");
        WebElement icon = driver.findElement(By.xpath(".//*[@id='gbwa']/div[1]/a"));
        icon.click();
        System.out.println("Link Clicked !!");
        Thread.sleep(10000);
        driver.close();
        }
        catch(Exception e)
        {
            System.out.println("Exception occurred : "+e);
            driver.close();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是执行上述脚本时的结果:[链接]

请告诉我点击事件未触发的原因及其解决方案。

Sig*_*hil 5

你犯了一个简单的错误:不building执行performing操作。Actions请注意,您已经创建了class的实例ob。正如名称所示,该类Actions定义了一组要执行的顺序操作。所以你必须为build()你的动作创建一个单一的Action动作perform()

下面的代码应该可以工作!

WebElement icon = driver.findElement(By.xpath(".//*[@id='gbwa']/div[1]/a"));
Actions ob = new Actions(driver);
ob.click(icon);
Action action  = ob.build();
action.perform();
Run Code Online (Sandbox Code Playgroud)

如果您查看下面给出的代码,首先移动到该icon元素,然后单击该元素,会更好地解释该类Actions

Actions ob = new Actions(driver);
ob.moveToElement(icon);
ob.click(icon);
Action action  = ob.build();
action.perform();
Run Code Online (Sandbox Code Playgroud)