Kannaライブラリを使用してswiftでhtml/xmlを解析

1005 ワード

  • ダウンロード:Podfileの中のファイルは
  • に参加します
    use_frameworks!
    pod 'Kanna', '~> 2.1.0'
    
  • pod install
  • import Kanna
    
    let html = "..."
    
    if let doc = HTML(html: html, encoding: .utf8) {
        print(doc.title)
        
        // Search for nodes by CSS
        for link in doc.css("a, link") {
            print(link.text)
            print(link["href"])
        }
        
        // Search for nodes by XPath
        for link in doc.xpath("//a | //link") {
            print(link.text)
            print(link["href"])
        }
    }
    
  • Github
  • 注意して、使用する時、あなたが探している要素が存在するかどうかを判断して、存在しなければ直接投げ間違えます.
  • //doc.css(".movie-txt>p>a")        
     if (doc.css(".movie-txt>p>a").count  != 0) {
               moive2.url = doc.css(".movie-txt>p>a")[0]["href"]!
               self.urlstr = moive2.url
            } else {
              //              
           }