I have this line of code in my HTML page: <a href="www.myWebsite.com" rel="ibox"></a>
.
How can I parse it in swift code in the best way, considering that I have not only this tag "a" but many?
I have this line of code in my HTML page: <a href="www.myWebsite.com" rel="ibox"></a>
.
How can I parse it in swift code in the best way, considering that I have not only this tag "a" but many?
Parsing HTML in Swift typically requires a third-party framework, personally, I use SwiftSoup.
Here's how you would parse that href
in Swift using SwiftSoup.
do {
let html = "<a href=\"www.myWebsite.com\" rel=\"ibox\"></a>"
let doc: Document = try SwiftSoup.parse(html)
let links = try doc.select("a").map {
try $0.attr("href")
} // ["www.myWebsite.com"]
} catch Exception.Error(let type, let message) {
print(message)
} catch {
print("error")
}
In the above, the links
array holds the values of all the links on a page.
import Foundation
let html = "theHtmlYouWannaParse"
var err : NSError?
var parser = HTMLParser(html: html, error: &err)
if err != nil {
println(err)
exit(1)
}
var bodyNode = parser.body
if let inputNodes = bodyNode?.findChildTags("b") {
for node in inputNodes {
println(node.contents)
}
}
if let inputNodes = bodyNode?.findChildTags("a") {
for node in inputNodes {
println(node.getAttributeNamed("href")) //<- Here you would get your files link
}
}