Upload file sử dụng Selenium WebDriver

Chào các bạn!

Chắc hẳn trong quá trình làm , cũng có lúc các bạn nhận gặp phải các tình huống cần tải tệp lên để tiếp tục các bước khác của test case như hình dưới đây:

Test case:

#StepsExpected results
1Navigate to the upload page The upload page is opened
2File explorer is opened and you need to select a file from desired location
Ex. File need to upload at D:\image\uploadFile.jpg
3Select a file type “Image” “Image” option is selected
4The file is uploaded successfully
upload_file

Như test case mô tả, bạn cần nhấp vào nút “Choose File” để mở File Explore và chọn file cần tải lên.

Có nhiều cách để tải file lên, nhưng ở bài này chúng ta sẽ chỉ tìm hiểu cách tải một file sử dụng phương thức sendKey() của nhé.

Cách tải một tập tin (file) sử dụng Selenium WebDriver

Xác định vị trí web element

Đầu tiên chúng ta sẽ quan sát mã html của phần tử web tải tệp tin lên sau đây

Web của “Choose File” được tạo bởi tag với type là “file

WebElement chooseFileBtn = driver.findElement(By.id("fileinput"));

Sử dụng phương thức sendKey()

Sau khi đã xác định được webelement của button “Choose File”, bạn chỉ cần sử dụng phương thức sendKeys() của selenium webdriver và truyền vào đối số là đường dẫn tuyệt đối của file đó. (Ví dụ: Image file cần tải lên được lưu lại ổ D -> D:\image\uploadFile.jpg)

chooseFileBtn.sendKeys("D:\\image\\uploadFile.jpg");

Kết quả sẽ hiển thị file name bên cạnh button “Choose File”

Code

package seleniumWebDriverExample;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class FileUpload {
    public static void main(String[] args) {
        // Lauching Chrome browser
        WebDriverManager.chromedriver().setup();
        WebDriver driver = new ChromeDriver();
        
        //  maximizing browser
        driver.manage().window().maximize();

        // Launching URL
        driver.get("https://testpages.herokuapp.com/styled/file-upload-test.html");

        // Locating input tag which as type as file.
        chooseFileBtn= driver.findElement(By.id("fileinput"));

        // Sending file name as argument to input tag
        chooseFileBtn.sendKeys("D:\\image\\uploadFile.jpg");

         // Select image option
        driver.findElement(By.cssSelector("input[value='image'][type='radio']"))click();
        
         // Click button "Upload"
        driver.findElement((By.cssSelector("[type='submit'][name='upload']")))click();
    }
}

  

      Kết quả là file đươc upload lên thành công sau khi bạn chạy đoạn code trên.

      Lưu ý:

      • Bài này mình chỉ tập trung vào việc tải file lên, không verify kết quả chạy (expect result) của từng step nhé.
      • Trong bài có dùng WebDriverManager, nếu bạn chưa biết có thể tham khảo tại đây.

      Good luck!

      Exit mobile version