Selenium webdriver 如何向浏览器上传文件?


借助 Selenium webdriver,我们可以向浏览器上传文件。通过对元素使用 sendKeys() 方法来实现,通过指定要上传的文件的路径,该方法执行文件的选择。

在使用文件上传功能时,我们需要点击“浏览”按钮。当元素的属性类型值为文件时,webdriver 会处理这一步。另外,要上传的文件的路径必须正确。

示例

代码实现。

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 FileUpld{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url ="https://tutorialspoint.com/selenium/selenium_automation_practice.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify element
      WebElement l=driver.findElement(By.xpath("//input[@name='photo']"));
      // file selection field with file path
      l.sendKeys("C:\Users\ghs6kor\Pictures\Tulips.jpg");
      driver.quit();
   }
}

输出

更新时间: 2020 年 8 月 28 日

993 次浏览

开始您的 职业

通过完成课程获得认证

开始
广告
© . All rights reserved.