selenium操作谷歌浏览器自定义下载文件保存路径

import java.util.HashMap;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;

public class test {

	public static void main(String[] args) throws InterruptedException {
		// 1.设置驱动路径
		System.setProperty("webdriver.chrome.driver", "webdriver/chromedriver.exe");

		// 2.设置下载文件存放路径
		String downloadPath = "D:\\Download";

		// 3.创建HashMap 保存下载文件存放路径
		HashMap<String, Object> hashMap = new HashMap<>();
		hashMap.put("download.default_directory", downloadPath);

		// 4.ChromeOptions 中设置下载路径信息,传入保存有下载路径的 HashMap
		ChromeOptions chromeOptions = new ChromeOptions();
		chromeOptions.setExperimentalOption("prefs", hashMap);

		// 依据 ChromeOptions 来产生 DesiredCapbilities,这时 DesiredCapbilities 也就具备了下载路径的信息
		DesiredCapabilities desiredCapabilities = new DesiredCapabilities();
		desiredCapabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
		chromeOptions.merge(desiredCapabilities);

		// 5.启动浏览器,带上chromeOptions 参数
		WebDriver driver = new ChromeDriver(chromeOptions);

		// 6.到目标网页
		driver.get("https://pypi.org/project/selenium/#files");
		driver.manage().window().maximize();
		
		// 7.定位到下载资源,点击下载
		WebElement element = driver.findElement(By.xpath("//a[contains(text(),'selenium-3.141.0.tar.gz')]"));
		element.click();
		Thread.sleep(10000);
		
		// 8.关闭浏览器
		driver.quit();

	}

}

你可能感兴趣的:(Java自动化)