在swift中解析html的最佳做法是什么?

时间:2015-06-26 19:31:52

标签: html ios swift parsing

我是斯威夫特的新手。我需要在Swift iOS项目中使用像Python的BeautifulSoup这样的东西。确切地说,我需要获得以href结尾的所有<a> ".txt"。我应该采取哪些步骤?

3 个答案:

答案 0 :(得分:80)

使用SwiftObjective-C有几个很好的 HTML Parsing 库,如下所示:

查看上面发布的四个库中的以下示例,主要使用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和CSS选择器)

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和CSS选择器)

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

ends-with函数是Xpath 2.0的一部分。

  

SwiftSoup(CSS选择器)

do{
    let doc: Document = try SwiftSoup.parse("...")
    let links: Elements = try doc.select("a[href]") // a with href
    let pngs: Elements = try doc.select("img[src$=.png]")

    // img with src ending .png
    let masthead: Element? = try doc.select("div.masthead").first()

    // div with class=masthead
    let resultLinks: Elements? = try doc.select("h3.r > a") // direct a after h3
} catch Exception.Error(let type, let message){
    print(message)
} catch {
   print("error")
}
  

Ji(XPath)

let jiDoc = Ji(htmlURL: URL(string: "http://www.apple.com/support")!)
let titleNode = jiDoc?.xPath("//head/title")?.first
print("title: \(titleNode?.content)") // title: Optional("Official Apple Support")

我希望这会对你有所帮助。

答案 1 :(得分:4)

你可以试试这个swift-html-parser:

https://github.com/tid-kijyun/Swift-HTML-Parser

它有很多帮助。

要从txt获取html,您可以:

let file = "file.txt"

if let dirs : [String] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String] {
    let dir = dirs[0] //documents directory
    let path = dir.stringByAppendingPathComponent(file);
    let html = String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil)

编辑:

为了得到你需要的东西你可以用作例子:

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

答案 2 :(得分:4)

尝试SwiftSoup,一个jsoup到Swift的端口。

let html: String = "<a id=1 href='?foo=bar&mid&lt=true'>One</a> <a id=2 href='?foo=bar&lt;qux&lg=1'>Two</a>";
    let els: Elements = try SwiftSoup.parse(html).select("a");
    for element: Element in els.array(){
        print(try element.attr("href"))
    }