简体   繁体   English

Selenium WebDriver和Java Robot类

[英]Selenium WebDriver and Java Robot Class

I want to use the Java Robot class in order to move the mouse over a link to dynamically create more content. 我想使用Java Robot类来将鼠标移到链接上以动态创建更多内容。 For the web interactions I use the Selenium WebDriver. 对于Web交互,我使用Selenium WebDriver。

    Point coordinates = driver.findElement(By.xpath("//li[@id='1234']/a")).getLocation();
    Robot robot;
    try {
        robot = new Robot();
        robot.mouseMove(coordinates.getX(),coordinates.getY()+120);
    } catch (AWTException e1) {
        e1.printStackTrace();
    }

Selenium throws an error for the getLocation function: Selenium引发getLocation函数错误:

Exception in thread "main" org.openqa.selenium.WebDriverException: Cannot determine size of element

Does anybody know what am I doing wrong? 有人知道我在做什么错吗?

mouseover action you can achieve ( Actions class) without using Robot also. 您可以在不使用Robot的情况下实现鼠标悬停动作( Actions类)。

new Actions(driver).moveToElement(driver.findElement(By.xpath("//li[@id='1234']/a"))).perform();

include below import statement in your file. 在文件中包含以下导入语句。

import org.openqa.selenium.interactions.Actions;

If you just want to make a mouse movement on the page, Selenium interactions can help you do the same. 如果您只想在页面上移动鼠标,Selenium交互可以帮助您完成此操作。

Here is the sample code for you 这是适合您的示例代码

WebElement myLink = driver.findElement(By.xpath("//li[@id='1234']/a"));

Actions act = new Actions(driver);
act.moveToElement(myLink).build().perform();

// if you want to click on the link : 
act.click(myLink).build().perform();

// if you want to move to the element and then click onthe link : 
act.moveToElement(myLink).click(myLink).build().perform();

// or can be done in two different steps like this : 
act = act.moveToElement(myLink);
act.click(myLink).build().perform()

For doing this we should import org.openqa.selenium.interactions.Actions; 为此,我们应该导入org.openqa.selenium.interactions.Actions;。

Hope this solves your problem. 希望这能解决您的问题。

I tried this and it seems to work for me. 我尝试了这个,它似乎为我工作。 Please check 请检查

Point p = webele.getLocation();
int x = p.getX();
int y = p.getY();
Dimension d = webele.getSize();
int h = d.getHeight();
int w = d.getWidth();
Robot r = new Robot();
r.mouseMove(x + (w/2), y+(h/2) +80);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM