【问题标题】:Selenium Java - moveToElement does not work in headless but works in chromeSelenium Java - moveToElement 在 headless 中不起作用,但在 chrome 中起作用
【发布时间】:2021-08-18 20:09:32
【问题描述】:

我有一个画布元素,我正在尝试使用以下代码将鼠标悬停在画布元素上。它在 Chrome 中运行良好。但是在无头浏览器中,moveToElement 步骤没有错误,但是鼠标悬停没有在我想要的偏移处执行。我什至设置了偏移量工作的窗口大小,但它仍然没有按预期工作


        Dimension bd = new Dimension(1296, 696);
        driver.manage().window().setSize(bd);
        canvasElementDimensions = driver.manage().window().getSize().toString();
        WebElement canvas = driver.findElement(By.xpath(canvasElementXpath));
        
        Dimension canvasDimension = canvas.getSize();    
        int canvas_center_x = canvasDimension.getWidth()/2;
        int canvas_center_y = canvasDimension.getHeight()/2;
        
        int mouse_hover_x = (canvas_center_x/-9)*2;
        canvasElementXOffset = String.valueOf(mouse_hover_x);
        int mouse_hover_y = (canvas_center_y/-9)*2;
        canvasElementYOffset = String.valueOf(mouse_hover_y);
        
        Actions action = new Actions(driver);
        action.moveToElement(canvas, mouse_hover_x, mouse_hover_y)
        .perform();

【问题讨论】:

  • 请向我们展示您设置为ChromeOptions opts = new ChromeOptions(); 的内容?
  • 尝试在执行移动后立即截屏,以确认无头页面是否真的看起来像它应该的样子
  • @Marek 我截图了,看起来一样。用户界面没有变化
  • @Prophet 我正在使用默认设置,我还没有设置 ChromeOptions

标签: java selenium selenium-chromedriver google-chrome-headless


【解决方案1】:

我不确定您要移动到哪里——要么移动到画布元素上方的特定位置,要么只是移动到元素的中间。 如果画布上方的位置对您来说无关紧要,我将删除所有偏移计算并仅使用以下内容:

Actions action = new Actions(driver);
action.moveToElement(canvas).perform();

由于基于JavaDoc,这会将指针移动到元素的中间:

moveToElement(WebElement toElement)

将鼠标移动到元素的中间。

【讨论】:

  • canvas 元素是一个圆环图,我需要将鼠标悬停在图表上才能查看工具提示。如果我将鼠标放在画布元素的中心,它不会显示工具提示。因此,在我的代码中,我尝试使用偏移值 moveToElement(canvas, mouse_hover_x, mouse_hover_y) 将鼠标悬停
【解决方案2】:

为了在无头模式下工作,您必须在 ChromeOptions 中设置几个设置。
在初始化浏览器驱动程序之前尝试此设置:

ChromeOptions opts = new ChromeOptions();
opts.setExperimentalOption("prefs", prefs);
opts.addArguments("--headless", "--disable-gpu", "--window-size=1920,1080","--ignore-certificate-errors","--no-sandbox", "--disable-dev-shm-usage");

driver = new ChromeDriver(opts);

【讨论】:

    【解决方案3】:

    在无头模式下,您实际上并没有 UI 元素。所有元素都是虚拟的,因此它们没有真实的位置和大小。

    尝试通过以下方式查找元素:

    • 身份证
    • CSS
    • Xpath

    找到元素后,只需执行以下操作:

    webElement.click();
    

    或者:

    new Actions(browser).moveToElement(element, 0, 0).click().build().perform();
    

    如果需要悬停再点击,悬停代码:

     Actions builder = new Actions(browser);
     builder.moveToElement(lastFoundElement).build().perform();
    

    通过 Xpath 或 CSS 在工具提示中找到下一个元素,然后单击它。

    【讨论】:

    • 我已经尝试过了,但它不起作用。我猜 moveToElement(element, 0, 0) 会移动到元素的中心。但就我而言,这行不通。我需要将鼠标悬停在偏移上才能查看工具提示
    • 为此你需要做clickAfterHover,看看我更新的答案
    猜你喜欢
    • 2017-11-09
    • 1970-01-01
    • 2019-10-30
    • 1970-01-01
    • 2016-04-04
    • 1970-01-01
    • 2017-11-14
    • 2015-03-31
    • 2015-12-13
    相关资源
    最近更新 更多