软件编程
位置:首页>> 软件编程>> java编程>> Java+Selenium实现文件上传下载功能详解

Java+Selenium实现文件上传下载功能详解

作者:洛阳泰山  发布时间:2021-06-23 23:33:23 

标签:Java,Selenium,文件,上传,下载

简介

本文主要讲解java代码如何利用selenium操作浏览器上传和下载文件代码教程。

上传文件

常见的 web 页面的上传,一般使用 input 标签或是插件(JavaScript、Ajax),对于 input 标签的上传,可以直接使用 sendKeys(路径) 来进行上传。

先写一个测试用的页面。

Java+Selenium实现文件上传下载功能详解

代码如下:

<!DOCTYPE html>
<html lang="en">

<head>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
</head>

<body>
   <input type="file" name="">
</body>
</html>

下面通过 xpath 定位 input 标签,然后使用 sendKeys(filePath) 上传文件。

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;

import java.awt.*;
import java.io.IOException;

public class SeleniumDemo {
   private final static String webDriver = "webdriver.chrome.driver";
   private final static String webDriverPath ="E:\\chromedriver\\chromedriver.exe";

public static void main(String[] args) throws InterruptedException, IOException, AWTException {
       System.setProperty(webDriver, webDriverPath);
       WebDriver driver= new ChromeDriver();
       driver.get("file:///C:/Users/liuya/Desktop/test.html");
       Thread.sleep(2000);
       String filePath="C:\\Users\\liuya\\Desktop\\doc\\tarzan.txt";
       driver.findElement(By.xpath("//*[@name='upload']")).sendKeys(filePath);

}

}

Java+Selenium实现文件上传下载功能详解

下载文件

Chrome浏览器

Firefox 浏览器要想实现文件下载,需要通过 add_experimental_option 添加 prefs 参数。

download.default_directory:设置下载路径。

profile.default_content_settings.popups:0 禁止弹出窗口。

Java+Selenium实现文件上传下载功能详解

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;

import java.awt.*;
import java.io.IOException;

public class SeleniumDemo {
   private final static String webDriver = "webdriver.chrome.driver";
   private final static String webDriverPath ="E:\\chromedriver\\chromedriver.exe";

public static void main(String[] args) throws InterruptedException, IOException, AWTException {
       System.setProperty(webDriver, webDriverPath);
       WebDriver driver= new ChromeDriver();
       driver.get("http://pic.sogou.com/d?query=%E5%B0%8F%E7%8B%97&forbidqc=&entityid=&preQuery=&rawQuery=&queryList=&st=&did=45");
       Thread.sleep(2000);
       driver.findElement(By.className("download")).click();
   }

}

当你弹出像下面的页面 &ldquo;您的连接不是私密连接&rdquo; 时,可以直接键盘输入 &ldquo;thisisunsafe&rdquo; 直接访问链接。那么这个键盘输入字符串的操作就是之间讲到的 sendKeys,但由于该标签页是新打开的,所以要通过 switchTo().window() 将窗口切换到最新的标签页。

//操作最新窗口
       driver.switchTo().window(driver.getWindowHandles().stream().reduce((first, second) -> second).orElse(null));
       driver.findElement(By.xpath("./html")).sendKeys("thisisunsafe");

Java+Selenium实现文件上传下载功能详解

来源:https://tarzan.blog.csdn.net/article/details/128601702

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com