今天我们主要学习的是不同的页面元素具有不同的Actions,例如一个按钮就可以具备“”单击“”Action,但是你无法在按钮上输入文字,如果在错误的页面元素上使用了无效的Actions,不会看到任何的错误提示信息并且相关的操作也不会被触发,因为WebDriver会忽略当前页面元素所不支持的Actions。

 

下面我们来一起学习下具体有哪些Actions:

1)sendkeys()

适用于具有文本编辑的页面元素,常见的方式是在文本输入框里面输入字符串。示例代码如下:

WebElement searchBox = driver.findElement(By.id("kw"));

searchBox.sendKeys("selenium");

// 输入大写字符串

searchBox.sendKeys(Keys.chord(Keys.SHIFT, "selenium"));

 

2)clear()

适用于具有文本编辑的页面袁术,作用是清除文本编辑区域中输入的文本信息,基本用法如下

WebElement searchBox = driver.findElement(By.id("kw"));

searchBox.clear();

 

3)submit()

适用于form或者form中的页面元素,作用是提交form到Web的服务器端。实例代码:

searchBox.submit();

 

4)isDisplayed()

适用于任何页面元素,用于判断页面元素是否可见。

// 判断百度输入框是否存在,存在为True

System.out.println(searchBox.isDisplayed());

 

5)isEnabled()

适用于任意的页面元素,用于判断该元素是否为启用状态。

 

6)isSelected()

适用于单选按钮、多选按钮,以及选项等页面元素,用于判断某个元素是否被选中。如果在其他页面元素上调用该方法。

 

7)适用于任意的页面元素,用于获取当前页面元素的属性。例如,百度页面的提交按钮“百度一下“:

 

WebElement searchButton = driver.findElement(By.id("su"));

System.out.println(searchButton.getAttribute("value"));

System.out.println(searchButton.getAttribute("class"));

System.out.println(searchButton.getAttribute("type"));

System.out.println(searchButton.getAttribute("id"));

输出如下:

 

百度一下

bg s_btn

submit

su

 

8)getText()

适用于任意元素,用于获取元素上的可见文本内容。如果文本内容为空,则该方法返回空。

WebElement sel_area = driver.findElement(By.id("areaID"));

System.out.println(sel_area.getText());

 

9)getTagName()

适用于任意元素,用于获取页面元素的tag name.其实就是获取HTML的标签名称

System.out.println(searchButton.getTagName());

输出:input

 

10)getCssValue()

适用于任意元素,用于获取当前页面元素的CSS元素属性,如cursor、font-family、font-size、height、background-color.

WebElement continueBtn = driver.findElement(By.name("continue"));

System.out.println("cssvalue" + continueBtn.getCssValue("height"));

输出:cssvalue21px

 

11)getLocation()

适用于页面任何元素,用于获取元素在页面的相对位置,其中坐标原点位于页面的左上角。

System.out.println(continueBtn.getLocation());

输出:(370, 8)

 

12)getSize()

适用于任何可见的页面元素,用于获取元素的宽度和高度信息,其返回值是一个包含(Width,height)的长宽组合。

System.out.println(continueBtn.getSize());

输出:(65, 21)