Reputation: 3600
I'm able to get the HTML from a URL and load it in a WKWebView, but I'm wanting to just load a single element from the HTML. In this case, that element is an aside, <aside class="col-sm-4 col-md-3 col-lg-3 sidebar">
My code for getting all of the HTML.
func getHTMLString() -> String? {
let urlString = "https://kyfb.com/\(county)"
guard let countyUrl = URL(string: urlString) else {
return nil
}
do {
let htmlString = try String(contentsOf: countyUrl, encoding: .isoLatin1)
return htmlString
} catch let error {
print("Error: \(error)")
return nil
}
}
The specific URL I'm trying is https://kyfb.com/jefferson. There is an aside there that has everything I'm wanting to show.
Upvotes: 0
Views: 512
Reputation: 9385
Extracting the element from the HTML code you downloaded is easy:
guard let html = getHTML()
else { return }
let regex = try! NSRegularExpression(pattern: "<aside class=\"col-sm-4 col-md-3 col-lg-3 sidebar\">([\\s\\S]*)</aside>")
let match = regex
.matches(in: html, range: NSRange(html.startIndex..., in: html))
.map {
html.substring(with: Range($0.range, in: html)!)
}
self.webView.loadHTMLString(match.first!, baseURL: nil)
The problem is that CSS/JS won't be captured. Another solution would be injecting Javascript and hiding every element except <aside></aside>
Upvotes: 2