简体   繁体   English

如何使用Selenium Webdriver JavaScript移动鼠标指针并单击?

[英]How to move the mouse pointer and click with Selenium Webdriver JavaScript?

I'm new in selenium and I'm facing problems with simple tasks. 我是硒的新手,我面临着一些简单任务的问题。

I'm trying to move the mouse to a specific area (x, y coordinates) in the page and then, click, but without success. 我试图将鼠标移到页面中的特定区域(x,y坐标),然后单击,但没有成功。 I did read the documentation and I'm using {bridge: true} because of the chromewebdriver. 我确实阅读了文档,由于使用了chromewebdriver,因此我正在使用{bridge: true}

Here is my code: 这是我的代码:

var webdriver = require('selenium-webdriver'),
  By = webdriver.By,
  until = webdriver.until,
  Origin = webdriver;


var driver = new webdriver.Builder()
  .forBrowser('chrome')
  .build();


driver.get('http://www.localhost:4000/');

var actions = driver.actions({ bridge: true });

actions.mouse().move({x: 400, y: 1100, duration: 2000, origin: Origin.VIEWPORT});

Another question. 另一个问题。 I know there is a fourth parameter origin origin: Origin.VIEWPORT , however, I don't know if I imported it correctly. 我知道有第四个参数origin origin: Origin.VIEWPORT ,但是,我不知道是否正确导入了它。

I also don't know how to trigger the click event since I have not any selected element. 我还不知道如何触发click事件,因为我没有任何选定的元素。 I want to click in the final mouse pointer position. 我要单击最终的鼠标指针位置。

It seems that you are missing the .perform(); 似乎您缺少.perform(); .

The classic way to do this is with Protractor 经典的方法是使用量角器

 // Instead of specifying an element as the target, you can specify an offset
// in pixels. This example double-clicks slightly to the right of an element.
browser.actions().
    mouseMove(element).
    mouseMove({x: 50, y: 0}).
    doubleClick().
    perform();

You can use mouseMove to the xy of the body element. 您可以使用mouseMove到body元素的xy。

Hope this helps you! 希望这对您有所帮助!

EDIT 编辑

If this doesn't work for you try something like this: 如果这对您不起作用,请尝试以下操作:

browser.actions() .mouseMove(element, { x: 20, y: 75, }) .perform().then(() => browser.actions() .click() .perform());

its works to me 它对我的作品

//定位一個按鈕
WebElement button = driver.findElement(By.xpath("//div[@class='page-button']"));
//new 一個移動滑鼠的物件
Actions clickAction = new Actions(driver).click(button);
//執行
clickAction.build().perform();
WebDriver driver = new FirefoxDriver();
JavascriptExecutor scpt = (JavascriptExecutor)driver;
scpt.executeScript("document.getElementById('[insert id]').click();");

Make sure you add a timer sleep in so it can let the page load and then be able to click afterwards so use Thread.Sleep(); 确保您添加了一个计时器休眠,以便它可以加载页面,然后可以随后单击,因此请使用Thread.Sleep();

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

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