1. 程式人生 > 實用技巧 >4.selenium之WebDriver常用方法

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