javascript - 通过 Selenium 驱动程序执行 Javascript elementFromPoint

标签 javascript c# selenium selenium-webdriver

我正在尝试为我的基于 Selenium 的框架实现一个“对象选择器”,这在大多数商业自动化工具中都很常见。为此,我使用 Javascript 命令在鼠标位置查找元素,但没有得到我期望的元素。

如果我使用 ChromeDriver 或 InternetExplorerDriver,脚本总是返回 header 对象。无论我看什么网页或鼠标的位置。尽管听起来脚本采用的是坐标 0、0 而不是鼠标位置,但我已确认 Cursor.Position 正在发送正确的值。

如果我使用的是 FirefoxDriver,我会遇到异常:

"Argument 1 of Document.elementFromPoint is not a finite floating-point value. (UnexpectedJavaScriptError)"

谁能看出我做错了什么?

    private void OnHovering()
    {
        if (Control.ModifierKeys == System.Windows.Forms.Keys.Control)
        {
            IWebElement ele = null;
            try
            {
                // Find the element at the mouse position
                if (driver is IJavaScriptExecutor)
                    ele = (IWebElement)((IJavaScriptExecutor)driver).ExecuteScript(
                        "return document.elementFromPoint(arguments[0], arguments[1])", 
                        new int[] { Cursor.Position.X, Cursor.Position.Y });

                // Select the element found
                if (ele != null)
                    SelectElement(ele);
            }
            catch (Exception) { }
        }
    }

谢谢!

最佳答案

实际上是关于如何将坐标传递到脚本中。 脚本参数必须单独指定为单独的 ExecuteScript() 参数。在您的案例中发生的事情是您基本上指定了一个 x 参数,这使得它认为 y 应该被视为默认 0 值。在 y=0 处通常有一个标题。

代替:

ele = (IWebElement)((IJavaScriptExecutor)driver).ExecuteScript(
                        "return document.elementFromPoint(arguments[0], arguments[1])", 
                        new int[] { Cursor.Position.X, Cursor.Position.Y });

你应该这样做:

ele = (IWebElement)((IJavaScriptExecutor)driver).ExecuteScript(
                        "return document.elementFromPoint(arguments[0], arguments[1])", 
                        Cursor.Position.X, Cursor.Position.Y);

关于javascript - 通过 Selenium 驱动程序执行 Javascript elementFromPoint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31910534/

相关文章:

python - 单元测试python中的软断言

JavaScript 网络推送 : where can I get "auth" key?

javascript - Angular : Directive Isolated Scope Undefined

c# - 跨多个程序集实现分部方法

javascript - Python爬虫使用Selenium和PhantomJS获取DOM信息

selenium - 如何通过 selenium webdriver 单击图像链接?

javascript - FB.ui 权限请求无法正常工作

javascript - 获取与请求

c# - Azure 存储事件触发器 - 捕获正在删除的 blob

c# - 建议正确的数据类型来存储用户的生日