提问者:小点点

如何使用Swift-Html-Parser获取Image src


我是Swift和Swift-超文本标记语言-Parser的新手。我正在使用Swift-超文本标记语言-Parser from:https://github.com/tid-kijyun/Swift-HTML-Parser

对于下面的问题,我需要一些帮助。

    let myURLString = "http://MytestingWebsite.com/MyAds.html"
    let myURL = NSURL(string: myURLString)

    var error: NSError?

    let myHTMLString = NSString(contentsOfURL: myURL, encoding: NSUTF8StringEncoding, error: &error)

    if let error = error {

        //for below question 2
        println("Error : \(error)")

    } else {

        // code

    }

1) How to get the Src of the Image if there is a) only one image b) a collection of images?  

      < image Src="....."/>

2) What to use to show message when there is an error?


Adding the the required files as per the above link for Swift-HTML-Parser :

1. Add a Bridging file. click Project and goto Building Setting 
Use search: type in Bridging 
Double click on the result : Objective-C Bridging Header 
and Click (+) at the Top to add.

Error msg show: When adding file name with (-) Like Swift-HTML-Parser-Bridging-Header.h 

So, I add SwiftHTMLParserBridgingHeader

2) Copy the File Swift-HTML-Parser-Bridging-Header.h and rename it as SwiftHTMLParserBridgingHeader.h in the project file.

3) Copy HTMLParser.Swift and HTMLNode.swift

4) Have added the reference Libxml2.dylib

When compile, (2) and (3) have red dot. Am I doing something wrong?




共1个答案

匿名用户

每个节点都有一个emum,您可以在超文本标记语言中搜索

public enum HTMLNodeType : String {
    case HTMLUnkownNode     = ""
    case HTMLHrefNode       = "href"
    case HTMLTextNode       = "text"
    case HTMLCodeNode       = "code"
    case HTMLSpanNode       = "span"
    case HTMLPNode          = "p"
    case HTMLLiNode         = "li"
    case HTMLUiNode         = "ui"
    case HTMLImageNode      = "image"
    case HTMLOlNode         = "ol"
    case HTMLStrongNode     = "strong"
    case HTMLPreNode        = "pre"
    case HTMLBlockQuoteNode = "blockquote"
}

从他们在网站上的例子来看:

var err : NSError?
//myHTMLString is the value you retrive from the website
var parser     = HTMLParser(html: myHTMLString, error: &err)
if err != nil {
    //This will log the error and exit the app
    //You probably should display an alert to the user
    println(err)
    exit(1)
}

var bodyNode   = parser.body

if let inputNodes = bodyNode?.findChildTags(HTMLNodeType.HTMLImageNode) {
    for node in inputNodes {
        println(node.contents)
        //this should display the address where the Image is
    }
}