且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在JAVA中使用JSOUP从HTML提取CSS样式

更新时间:2023-12-03 21:01:16

如果样式已嵌入到元素中,则只需使用.attr("style").

If the style is embedded in your Element you just have to use .attr("style").

JSoup不是HTML渲染器,它只是HTML解析器,因此您将不得不从检索到的<style>标签html内容中解析内容.您可以为此使用一个简单的正则表达式;但并非在所有情况下都有效.您可能要使用CSS解析器来完成此任务.

JSoup is not a Html renderer, it is just a HTML parser, so you will have to parse the content from the retrieved <style> tag html content. You can use a simple regex for this; but it won't work in all cases. You may want to use a CSS parser for this task.

public class Test {
    public static void main(String[] args) throws Exception {
        String html = "<HTML>\n" +
                "<HEAD>\n"+
                "<TITLE>Page 1</TITLE>\n"+
                "<META http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n"+
                "<DIV style=\"position:relative;width:931;height:1243;\">\n"+
                "<STYLE type=\"text/css\">\n"+
                "<!--\n"+
                "    .ft00{font-size:11px;font-family:Times;color:#ffffff;}\n"+
                "    .ft01{font-size:11px;font-family:Times;color:#ffffff;}\n"+
                "-->\n"+
                "</STYLE>\n"+
                "</HEAD>\n"+
                "</HTML>";

        Document doc = Jsoup.parse(html);
        Element style = doc.select("style").first();
        Matcher cssMatcher = Pattern.compile("[.](\\w+)\\s*[{]([^}]+)[}]").matcher(style.html());
        while (cssMatcher.find()) {
            System.out.println("Style `" + cssMatcher.group(1) + "`: " + cssMatcher.group(2));
        }
    }
}

将输出:

Style `ft00`: font-size:11px;font-family:Times;color:#ffffff;
Style `ft01`: font-size:11px;font-family:Times;color:#ffffff;