使用 Java 在 Selenium WebDriver 中聚焦元素的正确方法 [英] Correct way to focus an element in Selenium WebDriver using Java

查看:25
本文介绍了使用 Java 在 Selenium WebDriver 中聚焦元素的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

WebDriver 的 selenium.focus() 相当于什么?

What's the equivalent of selenium.focus() for WebDriver?

element.sendKeys("");

new Actions(driver).moveToElement(element).perform();

我已经尝试了这两种方法并且它们都有效,但是哪一种总是适用于所有元素?

I have tried both of them and they worked, but which one would always work on all elements?

对于任何元素(例如按钮、链接等),哪种方式是正确的?这对我很重要,因为该功能将用于不同的 UI.

Which one is the correct way for any elements (such as button, link etc.)? This matters to me because the function will be used on different UI's.

推荐答案

以下代码-

element.sendKeys("");

试图找到一个输入标签框来输入一些信息,而

tries to find an input tag box to enter some information, while

new Actions(driver).moveToElement(element).perform();

更合适,因为它适用于图像元素、链接元素、下拉框等.

is more appropriate as it will work for image elements, link elements, dropdown boxes etc.

因此,使用 moveToElement() 方法更有意义地关注网页上的任何通用 WebElement.

Therefore using moveToElement() method makes more sense to focus on any generic WebElement on the web page.

对于输入框,您必须click()要聚焦的元素.

For an input box you will have to click() on the element to focus.

new Actions(driver).moveToElement(element).click().perform();

对于链接和图像,鼠标将悬停在该特定元素上,您可以根据自己的需要决定单击().

while for links and images the mouse will be over that particular element,you can decide to click() on it depending on what you want to do.

如果输入标签上的 click() 不起作用 -

既然你希望这个函数是通用的,你首先检查 webElement 是否是一个输入标签 -

Since you want this function to be generic, you first check if the webElement is an input tag or not by -

if("input".equals(element.getTagName()){
   element.sendKeys("");
} 
else{
   new Actions(driver).moveToElement(element).perform();

}

您可以根据自己的喜好进行类似的更改.

You can make similar changes based on your preferences.

这篇关于使用 Java 在 Selenium WebDriver 中聚焦元素的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆