JAVA Selenium Webdriver在下载之前询问保存每个文件的位置

时间:2016-04-25 13:45:33

标签: java selenium browser selenium-webdriver

我正在尝试使用Selenium自动下载文件。

每当收到要下载的文件时,我都希望将该特定文件保存到自定义位置并使用自定义名称保存。

我希望浏览器要求保存每个文件,以便我可以动态提供自定义路径和文件名。

我能够将文件保存到自定义目录,但我无法控制文件名。我想使用java.awt.Robotjava.awt.datatransfer.StringSelectionjava.awt.Toolkit来使用自定义文件名。

  

我的代码

ChromeOptions chromeOptions = new ChromeOptions();
HashMap<String, Object> chromePreferences = new HashMap<String, Object>();
chromePreferences.put("profile.default_content_settings.popups", 0);
chromePreferences.put("download.default_directory", browserDownloadDirectoryPath);
chromePreferences.put("safebrowsing.enabled", "true");
chromeOptions.setExperimentalOption("prefs", chromePreferences);
chromeOptions.addArguments("--test-type");
chromeDesiredCapabilities = DesiredCapabilities.chrome();
chromeDesiredCapabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);

这是将文件保存到自定义文件夹。

如果浏览器要求保存文件,我想使用Robot Class发送路径。

StringSelection stringSelection = new StringSelection(
                "<file path>" + "<file name>");
Toolkit.getDefaultToolkit().getSystemClipboard()
                .setContents(stringSelection, null);

Robot robot = new Robot();

robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
robot.keyPress(KeyEvent.VK_DOWN);
robot.keyRelease(KeyEvent.VK_DOWN);
robot.keyPress(KeyEvent.VK_DOWN);
robot.keyRelease(KeyEvent.VK_DOWN);
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);

请提供强制浏览器请求保存文件的解决方案。

对于Firefox,我们about:config可以查看浏览器的所有首选项。对于其他浏览器我们也有这样的东西吗?

2 个答案:

答案 0 :(得分:5)

更好的方法是设置chrome以自动下载文件,然后等待新文件出现并最终重命名。

以下是通过单击链接下载PDF然后将其重命名为“mydocument.pdf”的示例:

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="grades" pageWidth="595" pageHeight="842" whenNoDataType="AllSectionsNoDetail" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="407ecd26-3880-4351-b7f4-4422fa5adc32">
    <style name="Crosstab Data Text" hAlign="Center"/>
    <queryString>
        <![CDATA[]]>
    </queryString>
    <field name="Subject" class="java.lang.String"/>
    <field name="Mark" class="java.lang.String"/>
    <field name="Grade" class="java.lang.String"/>
    <summary>
        <band height="50">
            <crosstab>
                <reportElement x="0" y="0" width="555" height="50" uuid="c15de662-be8e-4db4-acef-1b71c3201725"/>
                <crosstabHeaderCell>
                    <cellContents>
                        <staticText>
                            <reportElement style="Crosstab Data Text" x="0" y="0" width="70" height="30" uuid="07cab0ef-f928-4681-86ff-0c38656cdd31"/>
                            <box>
                                <pen lineWidth="0.5"/>
                                <topPen lineWidth="0.5"/>
                                <leftPen lineWidth="0.5"/>
                                <bottomPen lineWidth="0.5"/>
                                <rightPen lineWidth="0.5"/>
                            </box>
                            <textElement verticalAlignment="Middle"/>
                            <text><![CDATA[Subject]]></text>
                        </staticText>
                    </cellContents>
                </crosstabHeaderCell>
                <rowGroup name="dummy" width="70">
                    <bucket class="java.lang.String">
                        <bucketExpression><![CDATA["GRADE"]]></bucketExpression>
                    </bucket>
                    <crosstabRowHeader>
                        <cellContents backcolor="#F0F8FF" mode="Opaque">
                            <box>
                                <pen lineWidth="0.5" lineStyle="Solid" lineColor="#000000"/>
                            </box>
                            <textField>
                                <reportElement style="Crosstab Data Text" x="0" y="0" width="70" height="25" uuid="0ec80ead-fa81-4933-b56b-445e14578f6b"/>
                                <textElement verticalAlignment="Middle"/>
                                <textFieldExpression><![CDATA[$V{dummy}]]></textFieldExpression>
                            </textField>
                        </cellContents>
                    </crosstabRowHeader>
                    <crosstabTotalRowHeader>
                        <cellContents/>
                    </crosstabTotalRowHeader>
                </rowGroup>
                <columnGroup name="Subject" height="30">
                    <bucket class="java.lang.String">
                        <bucketExpression><![CDATA[$F{Subject}]]></bucketExpression>
                    </bucket>
                    <crosstabColumnHeader>
                        <cellContents backcolor="#F0F8FF" mode="Opaque">
                            <box>
                                <pen lineWidth="0.5" lineStyle="Solid" lineColor="#000000"/>
                            </box>
                            <textField>
                                <reportElement style="Crosstab Data Text" x="0" y="0" width="62" height="30" uuid="304f31c2-426d-4177-aa32-bb7f6694cd6c"/>
                                <textElement verticalAlignment="Middle"/>
                                <textFieldExpression><![CDATA[$V{Subject}]]></textFieldExpression>
                            </textField>
                        </cellContents>
                    </crosstabColumnHeader>
                    <crosstabTotalColumnHeader>
                        <cellContents/>
                    </crosstabTotalColumnHeader>
                </columnGroup>
                <measure name="GradeMeasure" class="java.lang.String">
                    <measureExpression><![CDATA[$F{Grade}]]></measureExpression>
                </measure>
                <crosstabCell width="62" height="25">
                    <cellContents>
                        <box>
                            <pen lineWidth="0.5" lineStyle="Solid" lineColor="#000000"/>
                        </box>
                        <textField>
                            <reportElement style="Crosstab Data Text" x="0" y="0" width="62" height="25" uuid="b10eac33-96fb-4d5d-8c3f-212c72192a3c"/>
                            <textElement verticalAlignment="Middle"/>
                            <textFieldExpression><![CDATA[$V{GradeMeasure}]]></textFieldExpression>
                        </textField>
                    </cellContents>
                </crosstabCell>
                <crosstabCell height="25" rowTotalGroup="dummy">
                    <cellContents backcolor="#BFE1FF" mode="Opaque">
                        <box>
                            <pen lineWidth="0.5" lineStyle="Solid" lineColor="#000000"/>
                        </box>
                        <textField>
                            <reportElement style="Crosstab Data Text" x="0" y="0" width="50" height="25" uuid="26fc7a85-7738-45e8-81ff-e076bb51d3fd"/>
                            <textFieldExpression><![CDATA[$V{GradeMeasure}]]></textFieldExpression>
                        </textField>
                    </cellContents>
                </crosstabCell>
                <crosstabCell width="50" columnTotalGroup="Subject">
                    <cellContents backcolor="#BFE1FF" mode="Opaque">
                        <box>
                            <pen lineWidth="0.5" lineStyle="Solid" lineColor="#000000"/>
                        </box>
                        <textField>
                            <reportElement style="Crosstab Data Text" x="0" y="0" width="50" height="25" uuid="82d05499-1fe2-4a97-ad82-23fa974759c5"/>
                            <textFieldExpression><![CDATA[$V{GradeMeasure}]]></textFieldExpression>
                        </textField>
                    </cellContents>
                </crosstabCell>
                <crosstabCell rowTotalGroup="dummy" columnTotalGroup="Subject">
                    <cellContents backcolor="#BFE1FF" mode="Opaque">
                        <box>
                            <pen lineWidth="0.5" lineStyle="Solid" lineColor="#000000"/>
                        </box>
                        <textField>
                            <reportElement style="Crosstab Data Text" x="0" y="0" width="50" height="25" uuid="c6e4a9d8-6c74-4dcc-8617-18ad14e60890"/>
                            <textFieldExpression><![CDATA[$V{GradeMeasure}]]></textFieldExpression>
                        </textField>
                    </cellContents>
                </crosstabCell>
            </crosstab>
        </band>
    </summary>
</jasperReport>

对于文件服务员:

// define the download folder
Path download_folder = Paths.get(System.getProperty("user.home") + "/Downloads");

// define the preferences
HashMap<String, Object> prefs = new HashMap<String, Object>();
prefs.put("download.default_directory", download_folder.toAbsolutePath());
prefs.put("download.prompt_for_download", false);
prefs.put("download.directory_upgrade", true);
prefs.put("plugins.plugins_disabled", new String[]{"Chrome PDF Viewer"});

// define the options
HashMap<String, Object> options = new HashMap<String, Object>();
options.put("prefs", prefs);

// define the capabilities
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability("chromeOptions", options);

// start the driver
WebDriver driver = new ChromeDriver(capabilities);

// click on a PDF link
driver.get("http://www.adobe.com/legal/terms.html");
driver.findElement(By.linkText("Adobe Creative SDK")).click();

// wait for the PDF to be downloaded
File file = WaitForNewFile(download_folder, ".pdf", 60);

// rename the downloaded file
file.renameTo(download_folder.resolve("mydocument.pdf").toFile());

// quit
driver.quit();

答案 1 :(得分:1)

为Chrome浏览器设置所需的功能。

<a href="#" onclick="addAdmin(event);">Submit</a>