Selenium 简明教程
Selenium WebDriver - File Upload
Selenium Webdriver 可用于自动化需要在网页上上传文件的测试。在 HTML 术语中,文件上传元素由称为 {s1} 的标签名称标识。此外,它应具有值为 {s3} 的属性 {s2}。
Selenium Webdriver can be used to automate tests requiring uploading files on a web page. In HTML terminology, a file upload element is identified by the tagname called input. Also, it should have a property type having the value as file.
Identify Upload Functionality in HTML
右键单击下方所示页面,然后单击 Chrome 浏览器中的“检查”按钮。结果,整个页面的完整 HTML 代码将可见。要检查页面上的“选择文件”按钮,请单击左上角箭头,如下所示。
Right click on the page shown below, and click on the Inspect button in the Chrome browser. As a result, the complete HTML code for the entire page would be visible. For inspecting the Choose file button on the page, click on the left upward arrow, as highlighted below.
单击并指向文本 {s4} 旁边的该按钮后,其 HTML 代码将可见,其中反映了 {s5} 标签名,以及值为 {s7} 的 {s6} 属性。
Once, we had clicked and pointed the arrow to that button beside the text Select a file, its HTML code was visible, reflecting the input tagname, and its type attribute having the value file.
<input id="uploadFile" type="file" lang="en" class="form-control-file">
要上传文件,我们将使用 {s8} 方法。要上传的文件的路径作为该方法的参数传递。
To upload a file, we would use the sendKeys() method. The path of the file to be uploaded is passed as a parameter to that method.
Example
让我们以以下页面为例,我们将在其中单击 {s10} 按钮上传文件 {s9}。成功上传后,文件 {s11} 应显示在网页上。
Let us take an example of the below page, where we would upload a file Picture.png by clicking the Choose file button. Once successfully uploaded, the file Picture.png should be visible on a web page.
Syntax
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());
代码实现
Code Implementation
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://www.tutorialspoint.com/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 文件中添加的依赖项:
Dependencies added in pom.xml file −
<?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>
Output
Getting the file path to be uploaded: /Users/IdeaProjects/Selenium Java/./Picture.png
File uploaded unsuccessfully
Process finished with exit code 0
在上述示例中,我们通过控制台中的消息 {s12} 获得了要上传的文件的路径。然后,我们通过控制台中的消息 {s13} 成功上传了文件。
In the above example, we had obtained the path of the file to be uploaded with the message in the console - Getting the file path to be uploaded: /Users/IdeaProjects/Selenium Java/./Picture.png. Then we had successfully uploaded the file with the message in the console - File uploaded unsuccessfully.
最后,收到了消息 Process finished with exit code 0 ,表示代码成功执行。
Finally, the message Process finished with exit code 0 was received, signifying successful execution of the code.
Exception with Incorrect File Path
让我们再举一个示例,其中将要上传的文件的错误路径作为参数传递给 sendKeys() 方法(即将上传的文件名命名为 {s14},而不是 Picture.png)。在这种情况下,将不会上传文件,并且会引发异常。
Let us take another example, where a wrong path of the file to be uploaded is passed as a parameter to the sendKeys() method(that is the file name to be uploaded is named as Picture1.png instead of Picture.png). In such a scenario, a file would not be uploaded, and an exception would be thrown.
Example
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://www.tutorialspoint.com/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
在上述示例中,我们通过控制台中的消息 {s15} 获得了要上传的文件的路径。然后收到异常,因为发送了不正确的文件路径以进行上传。
In the above example, we had obtained the path of the file to be uploaded with the message in the console - Getting the file path to be uploaded: /Users/IdeaProjects/Selenium Java/./Picture1.png. Then received the exception since an incorrect file path was sent for upload.
最后,收到了消息 Process finished with exit code 1 ,表示代码执行失败。
Finally, the message Process finished with exit code 1 was received, signifying unsuccessful execution of the code.
Conclusion
这总结了我们对 Selenium WebDriver 文件上传教程的全面理解。我们从描述 HTML 中的标识上传功能开始,并举例说明如何在 Selenium Webdriver 中上传文件。这使您具备对 Selenium WebDriver 文件上传的深入了解。明智的做法是实践您所学到的内容,并探索与 Selenium 相关的其他内容,以加深您的理解并扩大您的视野。
This concludes our comprehensive take on the tutorial on Selenium WebDriver File Upload. We’ve started with describing identify upload functionality in HTML, and examples to illustrate how to upload files in Selenium Webdriver. This equips you with in-depth knowledge of the Selenium WebDriver File Upload. It is wise to keep practicing what you’ve learned and exploring others relevant to Selenium to deepen your understanding and expand your horizons.