gpt4 book ai didi

javascript - 如何在 selenium 中使用 JavascriptExecutor 右键单击​​ svg 元素

转载 作者:行者123 更新时间:2023-11-28 05:24:31 25 4
gpt4 key购买 nike

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

背景图层中需要右键单击的部分有一些 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来点击任何不可见的元素。在找到这个之前,我尝试使用操作来执行上下文菜单单击,这给出了以下错误

Caused by: org.openqa.selenium.interactions.MoveTargetOutOfBoundsException: Offset within element cannot be scrolled into view: (2.5, 0.5): [object 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 is not a function

所以请帮我一下。我什至无法仅单击这个不可见的“线”元素。实际上我需要执行右键单击。

最佳答案

为了使用 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);

关于javascript - 如何在 selenium 中使用 JavascriptExecutor 右键单击​​ svg 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40279285/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com