【问题标题】:How to right click on a svg element using JavascriptExecutor in selenium如何在 selenium 中使用 JavascriptExecutor 右键单击​​ svg 元素
【发布时间】:2017-03-09 19:46:01
【问题描述】:

我必须右键单击网页的特定部分。

在我需要右键单击的部分的背景层中有一些 svg 元素。这些 svg 元素位于不可见的不同层中。下面是html代码

HTML Code of the svg elements

可见部分的 HTML 代码(图像中突出显示的 div 元素,其类值包含“z-Timeline-TimelineTrack”)如下所示(您还可以在下面的代码中看到 svg 元素部分) HTML code of visible part of webpage

如您所见,有许多“行”元素。我需要在指定的行上单击鼠标右键。

我可以使用下面的 xpath 来定位特定的线元素

@FindBy(xpath ="//*[name()='svg']//*[name()='line'][5]")
public WebElement anyAgendaLine;

在网上搜索后,我发现我可以使用 JavascriptExecutor 来点击任何不可见的元素。在找到这个之前,我尝试使用操作来执行上下文菜单单击,这给出了以下错误

原因: org.openqa.selenium.interactions.MoveTargetOutOfBoundsException: 元素内的偏移量无法滚动到视图中:(2.5,0.5): [对象 SVGLineElement]

我的上下文菜单点击代码如下:

public static void rightClickAndSelectMenuItem(WebElement objWebElement, WebElement menuItem){
        Actions action=new Actions(Setup.driver);
        action.contextClick(objWebElement).sendKeys(Keys.ARROW_DOWN).click(menuItem).build().perform();

}

在发现上下文菜单点击不起作用后,我尝试点击“line”元素:

(JavascriptExecutor js = (JavascriptExecutor)driver; 
js.executeScript("arguments[0].click();", objAgendaPage.anyAgendaLine); 

下面的错误

org.openqa.selenium.WebDriverException: arguments[0].click 不是 功能

所以请帮帮我。我什至不能只点击这个不可见的“线条”元素。 其实我需要执行一个右键单击。

【问题讨论】:

  • 请勿将截图作为代码,请把实际代码放入问题中
  • 能否添加页面相关部分的截图?是否可以使用坐标来使用上下文单击?就像从容器中找出位置一样?
  • @Liam 我只是认为这会使问题变得很长,而且人们可以通过使用图像快速而清晰地了解元素的层次结构..
  • @Grasshopper 很抱歉回复晚了。它现在正在使用你提到的方法。我得到了一个 SVG 元素的位置(objAgendaPage.anyAgendaLine),然后使用这些坐标右键单击可见的元素(objAgendaPage.timeLineTrack)...下面是代码.. actions.moveToElement(objAgendaPage.timeLineTrack, objAgendaPage.anyAgendaLine.getLocation().getX(), objAgendaPage.anyAgendaLine.getLocation().getY()) .contextClick().click(objAgendaPage.createAppointmentContextualTable).build().perform();
  • @Grasshopper 我无法直接右键单击 SVG 元素,因为它们位于隐藏的不同层中。因此我必须获取 SVG 元素的位置,然后右键单击该元素可见..非常感谢您的帮助..

标签: javascript html selenium svg selenium-webdriver


【解决方案1】:

为了使用 JavaScript 右键单击​​(在 this 的帮助下):

js.executeScript("function contextMenuClick(element){
var evt = element.ownerDocument.createEvent('MouseEvents');

var RIGHT_CLICK_BUTTON_CODE = 2;

evt.initMouseEvent('contextmenu', true, true,
     element.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, RIGHT_CLICK_BUTTON_CODE, null);

  if (document.createEventObject){
     // dispatch for IE
     return element.fireEvent('onclick', evt)
  }
  else{
     // dispatch for firefox + others
    return !element.dispatchEvent(evt);
  }
}; contextMenuClick();", objAgendaPage.anyAgendaLine);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-22
    • 2017-10-11
    • 1970-01-01
    • 2013-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多