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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13158705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 11:42:08  来源:igfitidea点击:

Extract CSS Styles from HTML using JSOUP in JAVA

javajsoup

提问by Yashpal Singla

Can anyone help with extraction of CSS styles from HTML using Jsoup in Java. For e.g in below html i want to extract .ft00 and .ft01

任何人都可以帮助使用 Java 中的 Jsoup 从 HTML 中提取 CSS 样式。例如,在下面的 html 中,我想提取.ft00 和 .ft01

<HTML>
<HEAD>
<TITLE>Page 1</TITLE>

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<DIV style="position:relative;width:931;height:1243;">
<STYLE type="text/css">
<!--
    .ft00{font-size:11px;font-family:Times;color:#ffffff;}
    .ft01{font-size:11px;font-family:Times;color:#ffffff;}
-->
</STYLE>
</HEAD>
</HTML>

回答by Alex

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

如果样式嵌入在您的元素中,您只需要使用.attr("style").

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.

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

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));
        }
    }
}

Will output:

将输出:

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

回答by Emmanuel Bourg

Try this:

试试这个:

Document document = Jsoup.parse(html);
String style = document.select("style").first().data();

You can then use a CSS parser to fetch the details you are interested in.

然后,您可以使用 CSS 解析器来获取您感兴趣的详细信息。