正确的方式来使用Java在Selenium WebDriver中集中一个元素 [英] Correct way to focus an element in Selenium WebDriver using Java

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

问题描述

对于WebDriver,相当于 selenium.focus()是什么?

  element.sendKeys(); 

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

我已经尝试了他们两个,他们工作,但哪一个总是会在所有元素上工作?

对于任何元素(如按钮,链接等),哪一个是正确的方法?这对我来说很重要,因为这个函数将被用在不同的UI上。

解决方案

b

element.sendKeys();



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

新的动作(驱动程序).moveToElement(element).perform();

更合适,因为它适用于图片元素,链接元素,下拉框等。

因此,使用moveToElement()方法更适合集中在网页上的任何通用WebElement。



对于输入框,您必须点击()才能关注元素。



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

而对于链接和图像,鼠标将在该特定的元素上,你可以决定点击()它取决于你想要做什么。



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



因为您希望此函数是通用的,您首先检查webElement是否是输入标记或不是 -

  if(input.equals(element.getTagName()){
element。 sendKeys();
}
else {
新操作(driver).moveToElement(element).perform();

}

您可以根据您的偏好进行类似的更改。


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

element.sendKeys("");

or

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

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

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.

解决方案

The following code -

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.

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

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.

If the click() on an input tag does not work -

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天全站免登陆