如何在Selenium中移动鼠标?

16

我想模拟鼠标沿着一个随机曲线或抛物线移动,以便看起来像鼠标实际上在页面上移动。使用Selenium,我只知道如何单击元素,但这不会在某些网站上模拟真实用户。我希望鼠标沿着我计算出的随机线移动,然后单击该元素。


使用Selenium点击元素时,有什么需要模拟的操作无法实现? - JeffC
鼠标移动 - raw-bin hood
3个回答

7
Python代码如下(假设您的浏览器是Firefox):
driver = webdriver.Firefox(executable_path=driver_path)
action = webdriver.ActionChains(driver)
element = driver.find_element_by_id('your-id') # or your another selector here
action.move_to_element(element)
action.perform()

请注意,这并不会移动您的物理光标,而仅移动Selenium的隐形光标。要查看是否有效,元素必须拥有某些“悬停”效果。 此外,如果您已经将光标移动到一个元素上,并希望相对重新定位它,则可以使用:
action.move_by_offset(10, 20)    # 10px to the right, 20px to bottom
action.perform()

甚至更短:

action.move_by_offset(10, 20).perform()

更多文档在此处: https://selenium-python.readthedocs.io/api.html


4

0

实际上,使用Webdriver进行测试后,模拟真实用户在网站上的操作是不可能的。这是因为鼠标不会执行“可见”的移动 :( 即使你通过代码让动作经过每个像素,也不起作用。

像下面这样的代码(可能存在以下代码中的错误)将无法正常工作。我尝试了一下,没有看到任何可见的鼠标移动。顺便说一句,在测试之后,我发现一旦传递参数给'moveByOffset',x和y坐标将从'左上角'点开始。也许首先移动到另一个元素没有用。

WebElement element = new WebDriverWait(driver, 10).until(ec);

    //Get the postion of the element 
    Point point = element.getLocation();

    int x = point.x;
    int y = point.y;


    //Let mouse on anther element
    WebElement element1 = driver.findElement(By.xpath("//a[@cid='link25118']"));
    Point point1 = element1.getLocation();
    int x1 = point1.x;
    int y1 = point1.y;
    action.moveToElement(element1);
    action.perform();

    //Calculate offset
    int offsetX = x1 - x > 0 ? x1 - x : x- x1;
    int offsetY = y1 - y > 0 ? y1 - y : y - y1;


    //Use move by offset to simulate moving along the element, then click
    int offset = offsetX > offsetY ? offsetX : offsetY;
    for(int i=0; i< offset; i++) {

        Thread.sleep(1000);

        if( i == (offsetX > offsetY ? offsetY : offsetX)) {
            if(offsetX > offsetY) {
                action.moveByOffset((offsetX - offsetY) * (x1>x?1:-1), 0).perform();
            } else {
                action.moveByOffset(0, (offsetY - offsetX) * (y1>y?1:-1)).perform();
            }

            break;
        }

        if((x1 > x) && (y1 > y)) {
            //right down
            action.moveByOffset(1, 1).perform();
        } else if ((x1 > x) && (y1 < y)) {
            //right up
            action.moveByOffset(1, -1).perform();
        } else if((x1 < x) && (y1 < y)) {
            //left up
            action.moveByOffset(-1, -1).perform();
        } else if ((x1 < x) && (y1 > y)) {
            //left down
            action.moveByOffset(-1, 1).perform();
        }
    }

    action.click();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接