gpt4 book ai didi

java - 如何让 onFocus() 用 Selenium 触发

转载 作者:行者123 更新时间:2023-11-30 16:55:23 24 4
gpt4 key购买 nike

我正在尝试使用 Selenium 测试 HTML 表单。该页面通过在每个文本字段(这是 HTML 中的输入标记)上使用 javascript 的 onFocus() 事件来验证输入数据。因此,我的代码需要确保每当我与文本字段交互时触发 onFocus(),就像真实用户填写表单一样。

我希望以下代码能够触发此事件:

this.textfield.clear();
if (value != null) {
this.textfield.sendKeys(value);
}

但是,onFocus() 事件不会触发。我试过手动点击元素

this.textfield.click()

但这也行不通。我也尝试过使用 Actions 类

this.textfield.clear();
Actions action = new Actions(driver);
action.moveToElement(this.textfield).click().sendKeys(value.toString()).perform();

但这也没有给我任何运气。

Selenium 中有什么方法可以确保执行 onFocus() 事件吗?

最佳答案

您可以在浏览器 session 中执行 JavaScript 以显式触发 onFocus()。此代码在 C# 中,但在 Java 绑定(bind)中也必须有类似的东西。

((IJavaScriptExecutor)driver).ExecuteScript(string.Format("$('#{0}').onFocus()", elementId));

关于java - 如何让 onFocus() 用 Selenium 触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29802476/

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