【问题标题】:How to parse a specific tag in swift如何快速解析特定标签
【发布时间】:2018-04-19 05:28:53
【问题描述】:

我的 HTML 页面中有这行代码:<a href="www.myWebsite.com" rel="ibox"></a>

考虑到我不仅有这个标签“a”而且还有很多,我如何才能以最好的方式在 swift 代码中解析它?

【问题讨论】:

标签: swift html-parsing


【解决方案1】:

在 Swift 中解析 HTML 通常需要第三方框架,我个人使用SwiftSoup

以下是您在 Swift 中使用 SwiftSoup 解析 href 的方法。

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")
}

Link to the documentation

在上面,links 数组保存了页面上所有链接的值。

【讨论】:

  • 如果我想检索 href 属性中的字符串? (所以在这种情况下是“www.myWebSite.com”)
  • 这就是上面所做的,在第 5 行
【解决方案2】:
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
    }
}

【讨论】:

  • 但我只想检索链接“www.myWebsite.com”而不是其他人
  • 让 html = "."
  • 也许我的问题写得不好。我想检索href中的字符串,但我不知道里面是什么。我只知道那是标签,它有属性rel="ibox"
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-20
  • 1970-01-01
  • 1970-01-01
  • 2019-04-11
  • 1970-01-01
  • 2016-12-06
相关资源
最近更新 更多