如何使用 Selenium Webdriver 上傳檔案?


我們可以使用 Selenium Webdriver 上傳檔案。這透過 sendKeys 方法實現。我們首先必須透過提及檔案路徑(要上傳的檔案)來識別執行檔案選擇的元素。

這僅應用於元素的 型別屬性設定為檔案作為值,同時元素標記名稱為輸入。以下 html 程式碼顯示了型別 = 檔案值設定的元素。

示例

程式碼實現。

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class WndsFileUpl{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();

      //implicit wait
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

      //launch application
      driver.get("https://tutorialspoint.tw/selenium/selenium_automation_practice.htm");

      // identify element
      WebElement m=driver.findElement(By.xpath("//input[@type='file']"));

      // windows file upload with file path
      m.sendKeys("C:\Users\Pictures\Logo.jpg");

      //browser close
      driver.close();
   }
}

輸出

更新於:22-11-2021

5K+ 瀏覽

啟動您的事業

完成課程,獲得認證

開始吧
廣告
© . All rights reserved.