有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用selenium下载POST响应文件

我的应用程序将在单击按钮时下载一个文件。 文件将在提交后下载,在提交之前无法获取文件的URL

我正在寻找一种使用selenium下载请求后附件的方法。有人可以指导我如何使用selenium Java实现这一点吗?。 enter image description here


共 (1) 个答案

  1. # 1 楼答案

    我不确定您的具体用例,但您是否喜欢这项工作?我做这个例子是为了下载谷歌浏览器。自动执行。就像你的文件一样,它也没有直接链接,只是由网站生成的下载

    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.chrome.ChromeOptions;
    
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.concurrent.TimeUnit;
    public class Main {
    
    
        public static void main(String[] args) {
            ChromeOptions options = new ChromeOptions();
            System.setProperty("webdriver.chrome.driver","where your ChromeDriver lives");
            Map<String, Object> prefs = new HashMap<String, Object>();
            prefs.put("download.default_directory", "where you want the file to be downloaded");
            prefs.put("download.prompt_for_download", false);
            options.setExperimentalOption("prefs", prefs);
            WebDriver driver = new ChromeDriver(options);
            String baseUrl = "https://www.google.com/chrome/";
            driver.get(baseUrl);
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch(Exception e){
    
            }
            List<WebElement> targetsWithClass = driver.findElements(By.className("chr-cta__button blue"));
            targetsWithClass.get(1).click();
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch(Exception e){
    
            }
            driver.findElement(By.id("js-accept-install")).click();
        }
    
    }