简体   繁体   English

如何使用 Selenium Webdriver 在网页中找到“光标”位置?

[英]How to find “Cursor” position in webpage with Selenium Webdriver?

I just started learning Selenium Webdriver using java Script, the question what I have asked might me a silly one.我刚开始使用 java Script 学习 Selenium Webdriver,我问的问题可能是一个愚蠢的问题。 But still wanted to know whether it is possible or not.但是还是想知道有没有可能。

As per my question, please go through the below example根据我的问题,请查看以下示例

In any Login page, enter valid "Username" and click on "signin" button, it throws an error message "Please enter password" and the "cursor" will be located in "Password" field在任何登录页面中,输入有效的“用户名”并单击“登录”按钮,它会抛出错误消息“请输入密码”并且“光标”将位于“密码”字段中

So, we can get the error message via code.所以,我们可以通过代码获取错误信息。 Now, how can we locate or identify the "Cursor" position in the webpage via code?现在,我们如何通过代码定位或识别网页中的“光标”位置?

By definition, any widget that has focus also has the cursor.根据定义,任何具有焦点的小部件也具有光标。 So driver.switchTo().activeElement() will return the currently focused WebElement.因此 driver.switchTo().activeElement() 将返回当前聚焦的 WebElement。 It doesn't actually change anything, just returns the active element.它实际上并没有改变任何东西,只是返回活动元素。 You can call你可以打电话

expectedElement.equals(driver.switchTo().activeElement());

to verify that expectedElement has focus.验证 expectedElement 是否具有焦点。

Hey user3313128 with Selenium Web driver library it is only possible to figure out the current position by knowing the last place you moved it to.嘿 user3313128 使用 Selenium Web 驱动程序库,只能通过知道您将其移动到的最后一个位置来确定当前位置。

Javascript sadly dose not give you an option to quickly get the X & Y.遗憾的是,Javascript 没有为您提供快速获取 X 和 Y 的选项。

An easy work around this is to simple run an simple function in the browser一个简单的解决方法是在浏览器中简单地运行一个简单的功能

async function (){
    await this.driver.executeScript(function(  ) { 
        let mouse = { x:0, y:0 }
        onmousemove = function(e){ mouse.x = e.clientX, mouse.y = e.clientY }
    })
}

this function will track your mouses X and Y in the browser the whole time此功能将始终在浏览器中跟踪您的鼠标 X 和 Y

Then when you need to know mouse's location just call this script然后当您需要知道鼠标的位置时,只需调用此脚本

mouse = driver.executeScript( function (){return mouse}) 

although the smart move is to track all of this within your JS on the server side at each mouse move and click().尽管明智的做法是在每次鼠标移动和 click() 时在服务器端的 JS 中跟踪所有这些。

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

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