java selenium 无弹窗,下载文件,格式是mht

本文介绍了如何使用Java Selenium在无弹窗的情况下下载MHT文件。当遇到有登录页面的情况,需要结合HttpGet和cookie来实现。通过获取cookie信息,然后对目标URL进行请求,并将MHT文件转换为HTML,以便于在非IE浏览器中打开。
摘要由CSDN通过智能技术生成

1.如果是单个网页,可以用下面的代码操作,下载网页,无弹窗。

package com.hlhlo.recruitment.download.service.impl;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.firefox.FirefoxProfile;

public class DownloadTest {

    public static void main(String[] args) {
        System.setProperty("webdriver.gecko.driver", "F:\\WebDriver\\geckodriver.exe");
        FirefoxProfile profile = new FirefoxProfile();

        // 可以在Firefox浏览器地址栏中输入about:config来查看属性
        // 设置下载文件放置路径,注意如果是windows环境一定要用\\,用/不行
        String path = "F:\\WebDriver\\download";

        // 配置响应下载参数
        profile.setPreference("browser.download.dir", path);// 下载路径
        profile.setPreference("browser.download.folderList", 2);// 2为保存在指定路径,0代表默认路径
        profile.setPreference("browser.download.manager.showWhenStarting", false);// 是否显示开始
        // 禁止弹出保存框,value是文件格式,如zip文件
        //常用的MIME类型   .mht .mhtml   message/rfc822
        profile.setPreference("browser.helperApps.neverAsk.saveToDisk","message/rfc822");
//关于类型:可以参考http://www.w3school.com.cn/media/media_mimeref.asp

        System.setProperty("webdriver.gecko.driver", "F:\\WebDriver\\geckodriver.exe");
        //WebDriver driver = new FirefoxDriver();

        FirefoxOptions options = new FirefoxOptions();
        options.setProfile(profile);
        WebDriver driver = new FirefoxDriver(options);
        //driver.get("file:///F:/dict_en_zhcn_2_pngs.rar");
        driver.get("file:///F:/a.mht");


    }


}

2.但是如果网页一开始有登录页面,然后打开其他网页,下载这个网页的东西,这个就不灵了,下载弹窗还是会打开。

如果另外新建一个WebDriver,又会提示先登录的信息。

所以解决方法是,用HttpGet直接下载,但是必须带上cookie,也就是带上登录信息才行。

step 1.现在获取cookie

 Set<Cookie> cookies = this.webDriver.manage().getCookies();
        StringBuffer cookieStr = new StringBuffer();
        for (Cookie cookie : cookies) {
            cookieStr.append(String.format("%s=%s;", cookie.getName(), cookie.getValue()));
        }
        this.cookie = cookieStr.toString();

step2.根据url得到对应网页的内容

/**
* 根据url下载页面
* @param url:下载的页面url
* @param cookie:网页的cookie,也就是登录信息。
**/
private String downloadByURL(String url,String cookie) {
        HttpGet get = new HttpGet(url);
        get.addHeader("Host", "jianli.58.com");
        get.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0");
        get.addHeader("Accept&
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值