如何使用 Selenium Webdriver 上传文件?
rest assureddynamic programmingprogramming
我们可以使用 Selenium Webdriver 上传文件。这通过 sendKeys 方法实现。首先,我们必须通过指定[待上传]文件路径来识别执行文件选择的元素。
这仅适用于将 type 属性设置为 file 且将元素标签名称作为输入的元素。以下 html 代码显示了设置了 type = file 值的元素。
示例
代码实现。
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(); //隐式等待 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); //启动应用程序 driver.get("https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm"); // 识别元素 WebElement m=driver.findElement(By.xpath("//input[@type='file']")); // Windows 文件上传(带文件路径) m.sendKeys("C:\Users\Pictures\Logo.jpg"); //浏览器关闭 driver.close(); } }