• Selenium Video Tutorials

Selenium WebDriver - 檔案上傳



Selenium WebDriver 可用於自動化需要在網頁上上傳檔案的測試。在 HTML 中,檔案上傳元素由名為input的標籤名稱標識。此外,它應該有一個屬性type,其值為file

在 HTML 中識別上傳功能

右鍵單擊下面顯示的頁面,然後單擊 Chrome 瀏覽器中的“檢查”按鈕。結果,整個頁面的完整 HTML 程式碼將可見。要檢查頁面上的“選擇檔案”按鈕,請單擊左側向上的箭頭,如下所示。

Selenium File Upload 1

單擊並將箭頭指向“選擇檔案”文字旁邊的按鈕後,其 HTML 程式碼可見,反映了input標籤名稱及其值為filetype屬性。

Selenium File Upload 2
<input id="uploadFile" type="file" lang="en" class="form-control-file">

要上傳檔案,我們將使用sendKeys()方法。要上傳的檔案路徑作為引數傳遞給該方法。

示例

讓我們以下面的頁面為例,我們將透過單擊“選擇檔案”按鈕上傳檔案Picture.png。成功上傳後,檔案Picture.png應該在網頁上可見。

Selenium File Upload 3

語法

WebDriver driver = new ChromeDriver();

// identify element the element 
WebElement l = driver.findElement(By.xpath("value of xpath locator"));

// getting file path to be uploaded
File f = new File("./Picture.png");
System.out.println("Getting the file path to be uploaded: " + f.getAbsolutePath());

// uploading file with path of file uploaded
m.sendKeys(f.getAbsolutePath());

程式碼實現

package org.example;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.File;
import java.util.concurrent.TimeUnit;

public class FilesUpload {
   public static void main(String[] args) throws InterruptedException {

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver();

      // adding implicit wait of 15 secs
      driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

      // Opening the webpage where we will upload a file
      driver.get("https://tutorialspoint.tw/selenium/practice/upload-download.php");

      // identify element with xpath for file upload
      WebElement m = driver.findElement(By.xpath("//*[@id='uploadFile']"));

      // getting file path to be uploaded
      File f = new File("./Picture.png");
      System.out.println("Getting the file path to be uploaded: " + f.getAbsolutePath());

      // uploading file with path of file uploaded
      m.sendKeys(f.getAbsolutePath());

      // check if file uploaded successfully
      if (m.getAttribute("value").equalsIgnoreCase("Picture.png")) {
         System.out.println("File uploaded successfully ");
      } else {
         System.out.println("File uploaded unsuccessfully ");
      }

      // Closing browser
      driver.quit();
   }
}

在 pom.xml 檔案中新增的依賴項:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
   http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>

   <groupId>org.example</groupId>
   <artifactId>SeleniumJava</artifactId>
   <version>1.0-SNAPSHOT</version>

   <properties>
      <maven.compiler.source>16</maven.compiler.source>
      <maven.compiler.target>16</maven.compiler.target>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
   </properties>
   
   <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
   <dependencies>
      <dependency>
         <groupId>org.seleniumhq.selenium</groupId>
         <artifactId>selenium-java</artifactId>
         <version>4.11.0</version>
      </dependency>
   </dependencies>
</project>

輸出

Getting the file path to be uploaded: /Users/IdeaProjects/Selenium Java/./Picture.png
File uploaded unsuccessfully 

Process finished with exit code 0

在上面的示例中,我們獲得了要上傳的檔案路徑以及控制檯中的訊息 - 正在獲取要上傳的檔案路徑:/Users/IdeaProjects/Selenium Java/./Picture.png。然後我們成功上傳了檔案,控制檯中的訊息為 - 檔案上傳失敗

最後,收到訊息程序已完成,退出程式碼為 0,表示程式碼已成功執行。

檔案路徑錯誤的異常

讓我們再舉一個例子,其中將錯誤的檔案路徑作為引數傳遞給 sendKeys() 方法(即要上傳的檔名為Picture1.png而不是 Picture.png)。在這種情況下,檔案將不會上傳,並且會丟擲異常。

示例

package org.example;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.File;
import java.util.concurrent.TimeUnit;

public class FilesExcUpload {
   public static void main(String[] args) throws InterruptedException {

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver();

      // adding implicit wait of 15 secs
      driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

      // Opening the webpage where we will upload a file
      driver.get("https://tutorialspoint.tw/selenium/practice/upload-download.php");

      // identify element with xpath for file upload
      WebElement m = driver.findElement(By.xpath("//*[@id='uploadFile']"));

      // getting file path to be uploaded
      File f = new File("./Picture1.png");
      System.out.println("Getting the file path to be uploaded: " + f.getAbsolutePath());

      // uploading file with path of file uploaded
      m.sendKeys(f.getAbsolutePath());

      // check if file uploaded successfully
      if (m.getAttribute("value").equalsIgnoreCase("Picture1.png")) {
         System.out.println("File uploaded successfully ");
      } else {
         System.out.println("File uploaded unsuccessfully ");
      }

      // Closing browser
      driver.quit();
   }
}

輸出

Getting the file path to be uploaded: 
   /Users/IdeaProjects/Selenium Java/./Picture1.png
Exception in thread "main"
   org.openqa.selenium.InvalidArgumentException: invalid argument: 
   File not found : /Users/IdeaProjects/Selenium Java/./Picture1.png

Process finished with exit code 1

在上面的示例中,我們獲得了要上傳的檔案路徑以及控制檯中的訊息 - 正在獲取要上傳的檔案路徑:/Users/IdeaProjects/Selenium Java/./Picture1.png。然後由於傳送了錯誤的檔案路徑進行上傳,因此收到異常。

最後,收到訊息程序已完成,退出程式碼為 1,表示程式碼執行失敗。

結論

本教程全面介紹了 Selenium WebDriver 檔案上傳。我們從描述如何在 HTML 中識別上傳功能開始,並透過示例來說明如何在 Selenium WebDriver 中上傳檔案。這使您深入瞭解 Selenium WebDriver 檔案上傳。明智的做法是繼續練習您所學的內容,並探索與 Selenium 相關的其他內容,以加深您的理解並拓寬您的視野。

廣告