Selenium:使用 C# 在 IWebElement 上触发鼠标滚轮

Posted

技术标签:

【中文标题】Selenium:使用 C# 在 IWebElement 上触发鼠标滚轮【英文标题】:Selenium: Trigger mousewheel on an IWebElement with C# 【发布时间】:2017-05-19 04:37:40 【问题描述】:

描述: 屏幕上显示的 html 元素(矩形)的复杂结构,没有重叠,每个矩形都有不同的 HTML id 属性(因此可由 Selenium IWebDriver 和 C# 代码选择)。

目标:我需要使用 Selenium 和 C# 以编程方式在 selected 矩形元素上创建和触发鼠标滚轮事件(通过 IjavascriptExecutor 或其他一些方法)。

问:如何做到这一点?谢谢

【问题讨论】:

【参考方案1】:

这是我调查后的实现

//wheelTicks: negative for zoomin, positive to zoomout 
public object zoomElementById(string elemId, int wheelTicks=1)

     object response = null;

     string myJavaScript =

            // Callback (place in first!) used to notify the caller that the async callee is ready
            "  var callback = arguments[arguments.length - 1];                                           " +
            "  var maxIntervals = arguments[1];                                                          " +
            //ms
            "  var intervalDuration = 150;                                                               " +
            "  console.log('javascripting...', callback, arguments);                                     " +

            "var d = new Date();                                                                         " +
            "var n = d.getTime();                                                                        " +

            "  var myZoomCenterElement = document.getElementById('" + elemId + "');                      " +
            // some debug output in the console 
            "  console.log(myZoomCenterElement);                                                         " +

            // *** THE CORE OF THE SOLUTION *** Creates proper WheelEvent object and triggers WheelEvent(Zoom)   
            "  var box = myZoomCenterElement.getBoundingClientRect();                                    " +    
            "  var boxMiddleX = Math.round((box.right + box.left )/2);                                   " +    
            "  var boxMiddleY = Math.round((box.bottom + box.top )/2);                                   " +
            "  var myWheelableElement = document.getElementsByClassName('svg-tree-view')[0];             " +
            "  var wheelEventInitDict =                                                                 " +
            "               'deltaX'    :      0.0,                                                      " +
            "               'deltaY'    :   -200.0,                                                      " +
            "               'deltaZ'    :      0.0,                                                      " +
            "               'deltaMode' :        0,                                                      " +
            "               'clientX'   :        boxMiddleX,                                             " +
            "               'clientY'   :        boxMiddleY                                              " +
            "               ;                                                                           " +
            "  var myWheelEvent = new WheelEvent('wheel', wheelEventInitDict);                           " +
            "  console.log(wheelEventInitDict, boxMiddleX, boxMiddleY, myWheelEvent);                    " +

            " var myIntervalCounter = 0;                                                                 " +
            " var myInterval = setInterval(function()                                                   " +
            "                    myWheelableElement.dispatchEvent(myWheelEvent);                         " +
            "                    myIntervalCounter++;                                                    " +
            "                    if (myIntervalCounter > maxIntervals) clearInterval(myInterval);        " +
            "                , intervalDuration);                                                       " +

            " var sthToReturn = 'Returning: Nothing requested!';                                         " +
            " var asyncAwaitInMiliSeconds = Math.ceil( 1.2 * intervalDuration * maxIntervals );          " +

            // Triggers the callback (to indicate async ready) 
            " setTimeout( function()                                                                    " +
            "                       console.log((new Date()).getTime()-n);                               " +
            "                       callback(sthToReturn);                                               " +
            "           , asyncAwaitInMiliSeconds);                                                     " +

            ""
            ;
     _driver.Manage().Timeouts().SetScriptTimeout(new TimeSpan(0, 0, 20));

     IJavaScriptExecutor js = _driver as IJavaScriptExecutor;
     try
     
            // addititonal args(optional) to be sent to the javascript func are put after the first arg 
            return response = js.ExecuteAsyncScript(myJavaScript, elemId, wheelTicks);

     
     catch(UnhandledAlertException e)
     
            Console.WriteLine("Error Occured! \n 0", e.ToString() );
            return null;
     
 

【讨论】:

以上是关于Selenium:使用 C# 在 IWebElement 上触发鼠标滚轮的主要内容,如果未能解决你的问题,请参考以下文章

Selenium:使用 C# 在 IWebElement 上触发鼠标滚轮

如何在 c# 中使用 Selenium 刷新网页?

C#使用Selenium

C# + Selenium + ChromeDriver 爬取网页

在 C# 中使用 Selenium WebDriver 执行 JavaScript

如何在 C# 中使用 Selenium 驱动程序向上/向下滚动页面?