如何在没有文本框的情况下在 Selenium 中上传文件?


我们可以在没有文本框的情况下在 Selenium 中上传文件。这是通过 sendKeys 方法实现的。它应用于执行选择要上传的文件路径的任务的 Web 元素上。

当我们尝试上传时,我们将单击浏览按钮。如果我们调查其 HTML 代码,我们将能够找到值 file 的属性 type。此外,要上传的文件路径应准确。

示例

代码实现。

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

输出

更新于: 2020 年 12 月 28 日

3K+ 浏览量

开启你的 职业生涯

完成课程,获得认证

开始学习
广告
© . All rights reserved.