selenide 取得下載檔案的路徑

selenide 是基於 selenium 建立的一個自動測試框架,它簡化了 selenium 的語法和環境設定,並且提供了更多的測試方式。

今天要來講的是 selenide 的檔案下載處理方式,在網頁被啟動時,selenide 會建立一個臨時的資料夾,用來存放本次測試下載的所有檔案

範例路徑:
    
C:\Users\Ruyut\Documents\work\demo\build\downloads\1655030879951_27668_1
    

但是如果要處理這個下載的檔案,就會變的很不方便,因為不知道確切的路徑 (當然可以取得該路徑下的最新資料夾來當作權變措施)

假設在程式中指定想要的下載路徑,但其實執行時裡面還是會再被建立一個資料夾,所以也沒有解決問題
  
Configuration.downloadsFolder = "C:\\Users\\Ruyut\\Downloads\\";


其實 selenide 有提供 download 方法,可以取得下載的檔案路徑,但是只限於有包含 href 屬性的連結
  
File file = getStockData.btnDownloadCsv.download();


不然會出現類似下列的錯誤:
  
java.lang.IllegalArgumentException: The element does not have href attribute:


所以最後使用這篇文章說明的方式解決
安裝依賴:
  
        <dependency>
            <groupId>com.codeborne</groupId>
            <artifactId>selenide</artifactId>
            <version>6.6.2</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.codeborne</groupId>
            <artifactId>selenide-proxy</artifactId>
            <version>6.6.2</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>net.lightbody.bmp</groupId>
            <artifactId>browsermob-core</artifactId>
            <version>2.1.5</version>
            <scope>test</scope>
        </dependency>


使用代理捕捉所有下載:
  
    @BeforeAll
    public static void setUpAll() {
        Configuration.downloadsFolder = "C:\\Users\\wusnn\\Downloads\\stock_backup\\"; // 修改預設資料夾

        BrowserMobProxy proxy = new BrowserMobProxyServer();
        proxy.start(0);

        Configuration.proxyEnabled = true;
        Configuration.fileDownload = PROXY;
    }


就可以使用 download 方法來取得下載檔案路徑了!
  
File file = getStockData.btnDownloadCsv.download(10000); // 取得下載檔案,最多等待 10秒


留言