使用jsoup检索html内联样式属性值

时间:2013-06-14 12:17:23

标签: java html jsoup

有人帮助我使用jsoup检索此示例中text-align样式的值吗?

<th style="text-align:right">4389</th>

这里我想得到值正确

谢谢!

3 个答案:

答案 0 :(得分:6)

您可以检索元素的style属性,然后按:拆分。

示例:

final String html = "<th style=\"text-align:right\">4389</th>";

Document doc = Jsoup.parse(html, "", Parser.xmlParser()); // Using the default html parser may remove the style attribute
Element th = doc.select("th[style]").first();


String style = th.attr("style"); // You can put those two lines into one
String styleValue = style.split(":")[1]; // TODO: Insert a check if a value is set

// Output the results
System.out.println(th);
System.out.println(style);
System.out.println(styleValue);

输出:

<th style="text-align:right">4389</th>
text-align:right
right

答案 1 :(得分:0)

提取样式属性的另一种方法是:

public Map<String, String> getStyleMap(Element element) {
    Map<String, String> keymaps = new HashMap<>();
    if (!element.hasAttr("style")) {
        return keymaps;
    }
    String styleStr = element.attr("style"); // => margin-top:-80px !important;color:#fcc;border-bottom:1px solid #ccc; background-color: #333; text-align:center
    String[] keys = styleStr.split(":");
    String[] split;
    if (keys.length > 1) {
        for (int i = 0; i < keys.length; i++) {
            if (i % 2 != 0) {
                split = keys[i].split(";");
                if (split.length == 1) break;
                keymaps.put(split[1].trim(), keys[i + 1].split(";")[0].trim());
            } else {
                split = keys[i].split(";");
                if (i + 1 == keys.length) break;
                keymaps.put(keys[i].split(";")[split.length - 1].trim(), keys[i + 1].split(";")[0].trim());
            }
        }
    }
    return keymaps;
}

将HashMap填充为:

0 = {HashMap$Node@5713} "background-color" -> "#333"
1 = {HashMap$Node@5714} "color" -> "#fcc"
2 = {HashMap$Node@5715} "font-family" -> "'Helvetica Neue', Helvetica, Arial, sans-serif"
3 = {HashMap$Node@5716} "margin-top" -> "-80px !important"
4 = {HashMap$Node@5717} "text-align" -> "center"

答案 2 :(得分:0)

public static Map<String, String[]> getStyleMap(String styleStr) {
    Map<String, String[]> keymaps = new HashMap<>();
    // margin-top:-80px !important;color:#fcc;border-bottom:1px solid #ccc; background-color: #333; text-align:center
    String[] list = styleStr.split(":|;");
    for (int i = 0; i < list.length; i+=2) {
        keymaps.put(list[i].trim(),list[i+1].trim().split(" "));
    }
    return keymaps;
}

结果:

0 = {HashMap$Node@5713} "background-color" -> ["#333"]
1 = {HashMap$Node@5714} "color" -> ["#fcc"]
2 = {HashMap$Node@5716} "margin-top" -> ["-80px","!important"]
3 = {HashMap$Node@5717} "text-align" -> ["center"]