簡體   English   中英

使用jsoup檢索html內聯樣式屬性值

[英]retrieve html inline style attribute value with jsoup

有人能幫我用 jsoup 檢索本例中 text-align 樣式的值嗎?

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

在這里,我想獲得的價值

謝謝!

您可以檢索元素的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

另一種提取樣式屬性的方法是:

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"
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"]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM