原文:軟測小生ruancexiaosheng 關(guān)注領(lǐng)取福利教程
CSDN博客原文
image.png
上一篇博客寫到當(dāng)不能使用Selenium來操作上傳下載接面的時(shí)候句柠,我們使用第三方AutoIt來搞定选泻。
Java+Selenium2+autoIt 實(shí)現(xiàn)Chrome右鍵文件另存為 功能
接下來我我要記錄一下今天學(xué)的使用Selenium更改Chrome默認(rèn)下載存儲路徑,當(dāng)然前提是在網(wǎng)頁上有下載鏈接直接點(diǎn)擊就會下載的级及,若不更改的話就會保存到Chrome默認(rèn)下載路徑下,有的時(shí)候?yàn)榱朔奖慊蚴呛罄m(xù)的使用饺律,我們需要更改一下保存路徑肌割,或者是將保存的文件路徑進(jìn)行動態(tài)、參數(shù)化的去傳入妓蛮,而不是固定的。
TestCase:
到Python的官網(wǎng),
下載selenium-3.13.0.tar.gz(版本可能會變化)到指定的文件路徑D:/dataSource/outputReport/Downloads
image.png
比較簡單圾叼,直接上代碼吧蛤克。
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默認(rèn)下載存儲路徑
System.setProperty("webdriver.chrome.driver", "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe");//設(shè)置驅(qū)動的路徑
DesiredCapabilities caps = setDownloadsPath();//更改默認(rèn)下載路徑
driver = new ChromeDriver(caps);
driver.manage().window().maximize();
driver.get("https://pypi.org/project/selenium/#files");//到目標(biāo)網(wǎng)頁
WebElement myElement = driver.findElement(By.xpath("http://a[contains(text(),'selenium-3.13.0.tar.gz')]"));
Actions action = new Actions(driver);
myElement.click();//點(diǎn)擊下載
Thread.sleep(10000);
}
//單獨(dú)重構(gòu)成一個(gè)方法捺癞,然后調(diào)用
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();
}
}