gpt4 book ai didi

javascript - 如何在 Selenium JavascriptExecutor 中执行脚本

转载 作者:行者123 更新时间:2023-11-29 19:44:02 25 4
gpt4 key购买 nike

我有一个 test.html 页面,这是它的代码。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
</head>
<body>
<span id="test" onMouseover="alert('1')">this is new one</span>
</body>
</html>

我想用Selenium JavascriptExecutor在测试页面的span上模拟鼠标悬停事件,所以我写了这样的代码:

@Test
public void testJSExecutor(){
System.setProperty("webdriver.firefox.bin", "C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");
webDriver = new FirefoxDriver();
webDriver.get("file:\\\\C:/test.html");

String script = "function test(){var t=document.getElementById('test');"
+ "if( document.createEvent ) {"
+ "var evObj = document.createEvent('MouseEvents');"
+ "evObj.initEvent( 'mouseover', true, false );"
+ "elem.dispatchEvent(evObj);"
+"} else if( document.createEventObject ) {"
+ "elem.fireEvent('onmouseover');"
+"}} window.onload=test;";
jsExecutor = (JavascriptExecutor) webDriver;
jsExecutor.executeScript(script);
}

但是运行这段代码后,没有提示提示。

鼠标悬停事件如何有效才能提示警报?

最佳答案

您可以使用以下代码模拟鼠标悬停 Action 。

Actions actions = new Actions(driver);
WebElement menuHoverLink = driver.findElement(By.id("test"));
actions.moveToElement(menuHoverLink);
actions.perform();

关于javascript - 如何在 Selenium JavascriptExecutor 中执行脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21178400/

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