對(duì)于上傳文件的用例,首先需要找到上傳文件的對(duì)象,然后直接往這個(gè)對(duì)象sendKeys,傳入需要上傳文件的正確路徑,路徑和相對(duì)路徑都可以的,但是上傳的文件必須存在,否則會(huì)報(bào)錯(cuò)。下面直接看例子吧:
| 
				 
					package org.coderinfo.demo; 
				
					import org.openqa.selenium.By; 
				
					import org.openqa.selenium.WebDriver; 
				
					import org.openqa.selenium.chrome.ChromeDriver; 
				
					/** 
				
					* @author Coderinfo 
				
					* @Email: coderinfo@163.com 
				
					*/ 
				
					public class UpdateFile { 
				
					private static final String URL = "file:///C:/Documents and Settings/user/Desktop/Selenium/update_file.html"; 
				
					public static void main(String[] args) { 
				
					WebDriver driver = new ChromeDriver(); 
				
					driver.manage().window().maximize(); 
				
					driver.get(URL); 
				
					// Use API:sendKeys to update file 
				
					driver.findElement(By.id("update")).sendKeys("C:/Documents and Settings/user/Desktop/Selenium/update_file.html"); 
				
					try { 
				
					Thread.sleep(10000); 
				
					} catch (InterruptedException e) { 
				
					e.printStackTrace(); 
				
					} 
				
					driver.close(); 
				
					} 
				
					} 
			 | 
		
本測(cè)試的頁(yè)面源碼:
| 
				 
					<!DOCTYPE html> 
				
					<html> 
				
					<head> 
				
					<title>Update File</title> 
				
					<style> 
				
					h2 { 
				
					text-align : center 
				
					} 
				
					</style> 
				
					</head> 
				
					<body> 
				
					<h2>Update File Demo</h2> 
				
					<form> 
				
					Update File:<input type="file" id="update"/> 
				
					</form> 
				
					</body> 
				
					</html> 
			 |