[英]We have set download directory in Chrome in selenium.But downloading control is going to downloads folder by default automatically
[英]How to set default download directory in selenium Chrome Capabilities?
請找到以下具有 chrome 功能的代碼。 實際上瀏覽器並沒有將文件下載到指定路徑。
private static DesiredCapabilities getChromeCapabilities() throws Exception {
String chromePath = BrowserUtil.class.getResource("/Browserdrivers/chromedriver.exe").getPath();
System.setProperty("webdriver.chrome.driver", chromePath);
String downloadFilepath = "C:\\TestDownloads";
ChromeOptions options = new ChromeOptions();
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("profile.default_content_settings.popups", 0);
chromePrefs.put("download.default_directory", downloadFilepath);
options.setExperimentalOption("prefs", chromePrefs);
options.addArguments("--test-type");
options.addArguments("start-maximized", "disable-popup-blocking");
DesiredCapabilities chromeCapabilities = DesiredCapabilities.chrome();
setProxy(chromeCapabilities);
chromeCapabilities.setPlatform(Platform.WINDOWS);
chromeCapabilities.setCapability("name", MDC.get("testname"));
chromeCapabilities.setCapability(ChromeOptions.CAPABILITY, options);
return chromeCapabilities;
}
對於 Chromedriver,請嘗試:
String downloadFilepath = "/path/to/download";
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("profile.default_content_settings.popups", 0);
chromePrefs.put("download.default_directory", downloadFilepath);
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", chromePrefs);
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
cap.setCapability(ChromeOptions.CAPABILITY, options);
WebDriver driver = new ChromeDriver(cap);
注意:- 在 Windows 中,您需要使用 \\\\ 作為路徑,而如果您使用的是 linux 或 mac,則使用 //
希望這可以幫助。 :)
對於看到此頁面的 Python 用戶——這是我在 Python Selenium 中設置下載目錄的方法(這只是 Shubham 接受的答案的 Python 版本):
def newChromeBrowser(headless=True, downloadPath=None):
""" Helper function that creates a new Selenium browser """
options = webdriver.ChromeOptions()
if headless:
options.add_argument('headless')
if downloadPath is not None:
prefs = {}
os.makedirs(downloadPath)
prefs["profile.default_content_settings.popups"]=0
prefs["download.default_directory"]=downloadPath
options.add_experimental_option("prefs", prefs)
browser = webdriver.Chrome(options=options, executable_path=CHROMEDRIVER_PATH)
return browser
幫助我在 Windows 上解決此問題的答案:( https://bugs.chromium.org/p/chromedriver/issues/detail?id=783 )。
Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put("download.default_directory", System.getProperty("user.dir")+ File.separator + "externalFiles" + File.separator + "downloadFiles");
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", prefs);
ChromeDriver driver = new ChromeDriver(options);
鉻:v84
Chrome 驅動程序:v83
JDK:OpenJDK 11 (LTS)
使用Paths類作為獨立於平台的文件分隔符。
@Test
public void doFileDownload() throws Throwable {
// Since Java 7: Relative path from project root dir
// Put in target dir to avoid committing downloaded files
var downloadDir = Paths.get("target").toAbsolutePath().toString();
var prefs = new HashMap<String, Object>();
prefs.put("download.default_directory", downloadDir); // Bypass default download directory in Chrome
prefs.put("safebrowsing.enabled", "false"); // Bypass warning message, keep file anyway (for .exe, .jar, etc.)
var opts = new ChromeOptions();
opts.setHeadless(true);
opts.setExperimentalOption("prefs", prefs);
var driver = new ChromeDriver(opts); // ChromeDriver binary is added to PATH env var
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("https://the-internet.herokuapp.com/download");
var downloadLink = driver.findElement(By.cssSelector("a[href*='some-file.txt']"));
var downloadHref = downloadLink.getAttribute("href").replace(":", "");
var downloadFileName = Paths.get(downloadHref).getFileName().toString();
downloadLink.click();
// Wait download to finish for 60s
var downloadFilePath = Paths.get(downloadDir, downloadFileName);
new WebDriverWait(driver, 60).until(d -> downloadFilePath.toFile().exists());
// Since Java 11: Read content of downloaded file
var content = Files.readString(downloadFilePath);
// Do tests with string content...
log.info("Content={}", content);
driver.quit();
}
輸出:
在任何運行之前執行mvn clean
還需要覆蓋現有文件。
pom.xml:
<properties>
<!-- Remove encoding warnings -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-server -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-server</artifactId>
<version>3.141.59</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.6.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<release>11</release>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
對於 Chrome 驅動程序,以下代碼對我有用
String downloadFilepath = "/path/to/download";
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("profile.default_content_settings.popups", 0);
chromePrefs.put("download.default_directory", downloadFilepath);
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", chromePrefs);
WebDriver driver = new ChromeDriver(options);
為了使它更簡潔,我開發了一個庫,它允許您生成一個 ChromeOptions 對象,該對象在一行中包含您的下載文件夾。 例如,要定義“/tmp/downloads”,請使用:
private SeleniumDownloadKPI seleniumDownloadKPI;
@BeforeEach
void setUpTest() {
// New instance of SeleniumDownloadKPI with given download folder.
seleniumDownloadKPI =
new SeleniumDownloadKPI("/tmp/downloads");
ChromeOptions chromeOptions =
seleniumDownloadKPI.generateDownloadFolderCapability();
driver = new ChromeDriver(chromeOptions);
該庫還包含允許接收下載 KPI 和執行斷言的方法。
使用 selenium 4(不確定是否可以使用早期版本,但認為可以)和 Chrome
(歐比旺克諾比的“百萬分之一”):
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setCapability("download.default_directory", "C:\\Users\\me\\Downloads");
driver =new ChromeDriver(chromeOptions);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.