首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用Selenium更改Chrome默认下载存储路径

使用Selenium更改Chrome默认下载存储路径

作者头像
软测小生
发布2019-07-05 10:48:46
2.9K0
发布2019-07-05 10:48:46
举报
文章被收录于专栏:软测小生软测小生

上一篇博客写到当不能使用Selenium来操作上传下载接面的时候,我们使用第三方AutoIt来搞定。 Java+Selenium2+autoIt 实现Chrome右键文件另存为 功能

接下来我我要记录一下今天学的使用Selenium更改Chrome默认下载存储路径,当然前提是在网页上有下载链接直接点击就会下载的,若不更改的话就会保存到Chrome默认下载路径下,有的时候为了方便或是后续的使用,我们需要更改一下保存路径,或者是将保存的文件路径进行动态、参数化的去传入,而不是固定的。

TestCase: 到Python的官网, 下载selenium-3.13.0.tar.gz(版本可能会变化)到指定的文件路径D:/dataSource/outputReport/Downloads

比较简单,直接上代码吧。

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.interactions.Actions;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;

public class testChromeDownload {
	WebDriver driver;

	@Test
	public void testOne() throws Exception {			
		//使用Chrome浏览器自动下载文件并保存到指定的文件路径
		//或 使用Selenium更改Chrome默认下载存储路径
		System.setProperty("webdriver.chrome.driver", "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe");//设置驱动的路径	
		DesiredCapabilities caps = setDownloadsPath();//更改默认下载路径		
		driver = new ChromeDriver(caps);
		driver.manage().window().maximize();
		driver.get("https://pypi.org/project/selenium/#files");//到目标网页		
		WebElement myElement = driver.findElement(By.xpath("//a[contains(text(),'selenium-3.13.0.tar.gz')]"));
		Actions action = new Actions(driver);
		myElement.click();//点击下载
		Thread.sleep(10000);
	}

	//单独重构成一个方法,然后调用
	public DesiredCapabilities setDownloadsPath() {
		String downloadsPath = "D:\\dataSource\\outputReport\\Downloads";
		HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
		chromePrefs.put("download.default_directory", downloadsPath);
		ChromeOptions options = new ChromeOptions();
		options.setExperimentalOption("prefs", chromePrefs);
		DesiredCapabilities caps = new DesiredCapabilities();
		caps.setCapability(ChromeOptions.CAPABILITY, options);
		return caps;
	}

	@AfterClass
	public void tearDown(){
		driver.quit();
	}
}
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2018-07-25,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 软测小生 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档