4.selenium之WebDriver常用方法

下面先来认识 WebDriver 中最常用的几个方法:

  • clear() 清除文本,方法用于清除文本输入框中的内容
  • sendKeys(*value) 模拟按键输入。键盘向输入框里输入内容。 但是它的作用不仅于此, 我们还可以用它发送键盘按键, 甚至用它来指定上传的文件。
  • click() 单击元素方法,前提是它是可以被单击的对象,它与 sendKeys()方法是Web页面操作中最常用到的两个方法。 其实click()方法不仅仅用于单击一个按钮,它还可以单击任何可以单击的文字/图片链接、复选框、单选框、下拉框等。
  • submit() 方法用于提交表单。 例如,在搜索框输入关键字之后的“回车” 操作, 就可以通过 submit()方法模拟.
  • import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.chrome.ChromeDriver;
     
    public class BaiduDemo {
     
      public static void main(String[] args) {
     
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.baidu.com/");
     
        WebElement search_text = driver.findElement(By.id("kw"));
        WebElement search_button = driver.findElement(By.id("su"));
     
        search_text.sendKeys("Java");
        search_text.clear();
        search_text.sendKeys("Selenium");
        search_button.click();
    //或者这样
    //WebElement search_text = driver.findElement(By.id("kw"));
    //search_text.sendKeys("Selenium");
    //search_text.submit();

    driver.quit();
      }
    }
  • getSize() 返回元素的尺寸。
  • getText() 获取元素的文本。
  • getAttribute(name) 获得属性值。
  • isDisplayed() 设置该元素是否用户可见.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;


public class BaiduDemo {
    public static void main(String[] args) {

        WebDriver driver = new ChromeDriver();
        driver.get("https://www.baidu.com/");

        //获得百度输入框的尺寸
        WebElement size = driver.findElement(By.id("kw"));
        System.out.println(size.getSize());

        //返回百度页面底部备案信息
        WebElement text = driver.findElement(By.cssSelector("#s-bottom-layer-right > span:nth-child(1)"));
        System.out.println(text.getText());

        //返回元素的属性值, 可以是 id、 name、 type 或元素拥有的其它任意属性
        WebElement ty = driver.findElement(By.id("kw"));
        System.out.println(ty.getAttribute("type"));

        //返回元素的结果是否可见, 返回结果为 True 或 False
        WebElement display = driver.findElement(By.id("kw"));
        System.out.println(display.isDisplayed());

        driver.quit();
    }
}
结果显示:
(548, 44) ©2020 Baidu text true
原文地址:https://www.cnblogs.com/peiminer/p/13559596.html