cssswiftswiftsoup

Get CSS value of a selector in Swift using SwiftSoup


I am using SwiftSoup library to parse a dynamically created HTML string in swift...

let doc = try SwiftSoup.parse(htmlString)

And let's say I have this result

<html>
    <head>
        <style>
            myClass {
                font-size: 14px;
                color: #000;
            }
        </style>
    </head>
    <body>
        <span class="myClass">Hello World</span>
    </body>
</html>

Now I can get the class value of my span like this

let span = try doc.select("body span")
let myClass = try span.attr("class")

Please is there a way I can iterate through the CSS attributes of myClass and get the attributes and their values.

Something like this:

var cssStyle = ""
let myClassAttrs = // a dictionary containing all myClass attributes(as dictionary keys) and values
for attr, value in myClassAttrs {
    cssStyle += "\(attr): \(value);"
}

Solution

  • do {
        let doc: Document = try SwiftSoup.parse(html)
        let span: Element = try doc.select("span.myClass").first()!
        let style: String = try span.attr("style")
        
        // Split the style attribute into an array of properties
        let properties = style.components(separatedBy: ";")
        
        // Iterate through the properties and print their names and values
        for property in properties {
            let components = property.components(separatedBy: ":")
            let name = components[0].trimmingCharacters(in: .whitespaces)
            let value = components[1].trimmingCharacters(in: .whitespaces)
            print("\(name): \(value)")
        }
    } catch {
        print("Error: \(error)")
    }
    

    This code first creates a Document object from the HTML string using SwiftSoup.parse(). It then selects the element with class myClass and retrieves its style attribute using Element.attr(). The style attribute is then split into an array of properties using components(separatedBy:). Finally, the code iterates through the properties, extracts their names and values using components(separatedBy:) again, and prints them to the console.