javajsouphtml-parsingcss-parsing

How to get the CSS style attribute from HTML content using Jsoup


I'm trying to get the Style attribute from the HTML div tag using Jsoup. See the below is my div tag.

<div id="badge" class="er-badge" style="width: 576px; height: 369px; background: url(&quot;http://localhost:1020/er/ERImg/firmUploads/13854/LogoImg4.png&quot;) 0% 0% / cover no-repeat; z-index: 1; position: relative;" tabindex="0" data-preview-purposes="checked">

from this div tag style I want to extract only the background: attribute. I can fetch the entire style properties using below code

String style = Element.attr("style");

But, I want to fetch only the background attribute value from this. Is it possible to extract that using Jsoup or Please tell any other easy way to extract the attribute. Thanks in advance.


Solution

  • Happy to see this question instead of someone trying to use Regex to parse manually.

    Just like we should not parse html ourself, parsing CSS manually is also undesired.

    There is already available library - cssparser htmlunit-cssparser to do the job. We can get the CSS value of background as below:

    import org.htmlunit.cssparser.dom.CSSStyleDeclarationImpl;
    import org.htmlunit.cssparser.parser.CSSOMParser;
    import org.jsoup.Jsoup;
    import org.jsoup.nodes.Element;
    
    import java.io.IOException;
    
    public class ParseStyle {
        public static void main(String[] args) throws IOException {
            Element e = Jsoup.parseBodyFragment("""
                    <div id="badge" class="er-badge" style="width: 576px; height: 369px; background: url(&quot;http://localhost:1020/er/ERImg/firmUploads/13854/LogoImg4.png&quot;) 0% 0% / cover no-repeat; z-index: 1; position: relative;" tabindex="0" data-preview-purposes="checked"> 
                     """);
            String style = e.select("div").attr("style");
            CSSOMParser parser = new CSSOMParser();
            CSSStyleDeclarationImpl decl = parser.parseStyleDeclaration(style);
            System.out.println(decl.getPropertyCSSValue("background"));
        }
    }