java Selenium 設置文件默認存儲路徑


轉自:https://blog.csdn.net/zbj18314469395/article/details/81207268

直接上代碼:

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();
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM