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



我试图在Java selenium的本地应用程序中下载单击操作文件。我在Ubuntu操作系统中执行Java代码。

我的代码片段如下,(我在java硒中使用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的本地目录。

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");

最新更新