在Ubuntu OS中使用Java selenium在Chrome中下载点击操作文件

v8wbuo2f  于 2023-04-20  发布在  Java
关注(0)|答案(1)|浏览(121)

我试图下载一个文件点击操作在我的本地应用程序在Java selenium 。我执行Java代码在Ubuntu操作系统。
我的代码片段如下,(我在java selenium中使用chrome驱动程序)

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.*;

public class Downloadfile {

public static void main(String[] args) throws IOException, InterruptedException {

try{
        String downloadFilepath = "/tmp/"; **==> custom file directory in ubuntu OS**
    HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
    chromePrefs.put("profile.default_content_settings.popups", 0);
    chromePrefs.put("download.default_directory", downloadFilepath);

    System.setProperty("webdriver.chrome.driver", "/usr/bin/chromedriver");
    ChromeOptions chromeOptions = new ChromeOptions();
    chromeOptions.addArguments("--headless");
    chromeOptions.addArguments("--no-sandbox");
    chromeOptions.setExperimentalOption("prefs", chromePrefs);

    
    WebDriver driver = new ChromeDriver(chromeOptions);
    driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

    driver.get("localhost:8080"); **// my custom application URL**
    driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

    WebElement element=driver.findElement(By.xpath("/html/body/div/div/div/div[2]/div/main/section/div[1]/div[1]")); 
   ((JavascriptExecutor) driver).executeScript("arguments[0].click();", element); **// this click operation will download a json file**

    driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
   
    driver.quit();
}catch(Exception e) {
    System.out.println(e);
}
}
}

我面临的问题,文件不下载到我的本地目录在Ubuntu。

kse8i1jr

kse8i1jr1#

Chrome可能没有该文件的必要权限,请在代码中更新ChromeOptions,如下所示:

ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--headless");
chromeOptions.addArguments("--no-sandbox");
chromeOptions.addArguments("--disable-dev-shm-usage");
chromeOptions.addArguments("--disable-extensions");
chromeOptions.addArguments("--disable-gpu");
chromeOptions.addArguments("--window-size=1920,1080");
chromeOptions.setExperimentalOption("prefs", chromePrefs);

chromeOptions.addArguments("--enable-features=NetworkServiceInProcess");
chromeOptions.addArguments("--disable-features=NetworkService");

相关问题