selenium java maven 自动化测试(二) 页面元素获取与操作

在第一节中,我们已经成功打开了页面,但是自动化测试必然包含了表单的填写与按钮的点击. 所以在第二章中我以博客园为例,完成按钮点击,表单填写

还是以代码为准,先上代码:

package com.ryan;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class Demo {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", ".\\tools\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("http://www.cnblogs.com/ryan255/");
        System.out.println(driver.getTitle());

     //获取页面上的按钮 WebElement button
= driver.findElement(By.cssSelector("#blog_nav_admin"));
     //点击按钮 button.click();
     //获取页面上的输入框   WebElement input1
= driver.findElement(By.cssSelector("#input1"));
     //清理输入框的内容 input1.clear();
     //输入 input1.sendKeys(
"ryan255");
     Thread.sleep(5000);  driver.quit(); } }

如上面的注释所示这里的代码增加了获取页面元素、点击按钮、输入表单的操作。

Selenium提供了8种定位方式:
  • id
  • name
  • class name
  • tag name
  • link text
  • partial link text
  • xpath
  • css selector
这8种定位方式在代码中所对应的方法为:
  • findElement(By.id())
  • findElement(By.name())
  • findElement(By.className())
  • findElement(By.tagName())
  • findElement(By.linkText())
  • findElement(By.partialLinkText())
  • findElement(By.xpath())
  • findElement(By.cssSelector())

猜你喜欢

转载自www.cnblogs.com/ryan255/p/9384808.html
今日推荐