> hpple
> NDHpple
> Kanna( old Swift-HTML-Parser)
> Fuzi
看看下面的例子,在上面发布的四个图书馆里,主要使用XPath 2.0进行解析:
hpple:
let data = NSData(contentsOffile: path)let doc = TFHpple(HTMLData: data)if let elements = doc.searchWithXPathquery("//a/@href[ends-with(.,'.txt')]") as? [TFHppleElement] { for element in elements { println(element.content) }}
NDHpple:
let data = NSData(contentsOffile: path)!let HTML = Nsstring(data: data,enCoding: NSUTF8StringEnCoding)!let doc = NDHpple(HTMLData: HTML)if let elements = doc.searchWithXPathquery("//a/@href[ends-with(.,'.txt')]") { for element in elements { println(element.children?.first?.content) }}
Kanna (Xpath and CSS Selectors):
let HTML = "<HTML><head></head><body><ul><li><input type='image' name='input1' value='string1value' class='abc' /></li><li><input type='image' name='input2' value='string2value' class='def' /></li></ul><span class='spantext'><b>Hello World 1</b></span><span class='spantext'><b>Hello World 2</b></span><a href='example.com'>example(English)</a><a href='example.co.jp'>example(JP)</a></body>"if let doc = Kanna.HTML(HTML: HTML,enCoding: NSUTF8StringEnCoding) { var bodyNode = doc.body if let inputNodes = bodyNode?.xpath("//a/@href[ends-with(.,'.txt')]") { for node in inputNodes { println(node.contents) } }}
Fuzi (Xpath and CSS Selectors):
let HTML = "<HTML><head></head><body><ul><li><input type='image' name='input1' value='string1value' class='abc' /></li><li><input type='image' name='input2' value='string2value' class='def' /></li></ul><span class='spantext'><b>Hello World 1</b></span><span class='spantext'><b>Hello World 2</b></span><a href='example.com'>example(English)</a><a href='example.co.jp'>example(JP)</a></body>"do { // if enCoding is omitted,it defaults to NSUTF8StringEnCoding let doc = try HTMLdocument(string: HTML,enCoding: NSUTF8StringEnCoding) // XPath querIEs for anchor in doc.xpath("//a/@href[ends-with(.,'.txt')]") { print(anchor.stringValue) }} catch let error { print(error)}
结束功能是Xpath 2.0的一部分。
我希望这能帮助你。
总结以上是内存溢出为你收集整理的在swift中解析html的最佳做法是什么?全部内容,希望文章能够帮你解决在swift中解析html的最佳做法是什么?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)