Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

java - How can I tell HtmlUnit's WebClient to download images and css?

How can I make WebClient download external css stylesheets and image bodies just like a usual web browser does?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

What I'm doing right now is:

public static final HashMap<String, String> acceptTypes = new HashMap<String, String>(){{
        put("html", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        put("img", "image/png,image/*;q=0.8,*/*;q=0.5");
        put("script", "*/*");
        put("style", "text/css,*/*;q=0.1");
    }};

protected void downloadCssAndImages(HtmlPage page) {
        String xPathExpression = "//*[name() = 'img' or name() = 'link' and @type = 'text/css']";
        List<?> resultList = page.getByXPath(xPathExpression);

        Iterator<?> i = resultList.iterator();
        while (i.hasNext()) {
            try {
                HtmlElement el = (HtmlElement) i.next();

                String path = el.getAttribute("src").equals("")?el.getAttribute("href"):el.getAttribute("src");
                if (path == null || path.equals("")) continue;

                URL url = page.getFullyQualifiedUrl(path);

                WebRequestSettings wrs = new WebRequestSettings(url);
                wrs.setAdditionalHeader("Referer", page.getWebResponse().getRequestSettings().getUrl().toString());

                client.addRequestHeader("Accept", acceptTypes.get(el.getTagName().toLowerCase()));
                client.getPage(wrs);
            } catch (Exception e) {}
        }



client.removeRequestHeader("Accept");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...