11/08/2018, 19:32

Thao tác với bàn phím trong Selenium

Kéo và thả trong Selenium Chúng ta sẽ thực hiện thao tác với bàn phím trong Selenium bằng việc sử dụng phương thức WebElement. sendKeys () hoặc Actions. sendKeys (). Send keys để biểu diễn bàn phím trong trình duyệt. Các phím đặc biệt không phải là văn bản, được biểu thị bằng Khóa ...

Kéo và thả trong Selenium

Chúng ta sẽ thực hiện thao tác với bàn phím trong Selenium bằng việc sử dụng phương thức WebElement.sendKeys() hoặc Actions.sendKeys(). Send keys để biểu diễn bàn phím trong trình duyệt. Các phím đặc biệt không phải là văn bản, được biểu thị bằng Khóa được nhận dạng như là một phần của chuỗi ký tự hoặc ký tự riêng lẻ.

Ví dụ

Sau đây là ví dụ thực hiện thao tác với bàn phím trong Selenium để mở trang https://google.com, nhập từ khóa ‘viettuts.vn’ rồi bấm phím Enter để thực hiện tìm kiếm.

1. Sử dụng phương thức Actions.sendKeys():

package vn.viettuts.selenium;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

public class KeyBoardDemo1 {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", 
                "D:SeleniumWebdriverchromedriver.exe");
        WebDriver driver = new ChromeDriver();

        // Open website
        driver.get("https://google.com");

        // Maximize the browser
        driver.manage().window().maximize();
        
        WebElement searchElement = driver.findElement(By.name("q"));
        searchElement.sendKeys("viettuts.vn");
        Actions action = new Actions(driver);
        action.sendKeys(Keys.RETURN);
        action.perform();
    }
}

Kết quả:

Ví dụ Thao tác với bàn phím trong Selenium

2. Sử dụng phương thức WebElement.sendKeys():

package vn.viettuts.selenium;

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

public class KeyBoardDemo2 {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", 
                "D:SeleniumWebdriverchromedriver.exe");
        WebDriver driver = new ChromeDriver();

        // Open website
        driver.get("https://google.com");

        // Maximize the browser
        driver.manage().window().maximize();
        
        WebElement searchElement = driver.findElement(By.name("q"));
        searchElement.sendKeys("viettuts.vn", Keys.RETURN);
    }
}

Kết quả:

Ví dụ Thao tác với bàn phím trong Selenium
Kéo và thả trong Selenium
0