我正在尝试使用 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();
}
}
}
这是执行上述脚本时的结果:[link]
但是,当使用 WebElement 接口(interface)的 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();
}
}
}
这是执行上述脚本时的结果:[link]
请告知点击事件未触发的原因及解决方法。
最佳答案
您犯了一个简单的错误,没有构建
和执行
操作。
请注意,您已经创建了 Actions
类 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();
如果您查看下面给出的代码,首先移动到 icon
元素,然后单击该元素,则可以更好地解释 Actions
类。
Actions ob = new Actions(driver);
ob.moveToElement(icon);
ob.click(icon);
Action action = ob.build();
action.perform();
关于selenium - 操作类 - 单击(WebElement ele)函数不单击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33179670/