如何使用Swift从URL获取HTML源代码

时间:2022-12-04 15:43:16

I need to look at the HTML of a page given by a certain URL. If I have this, what is the most efficient and synchronous way to get the HTML source for that URL using Swift? I haven't been able to find a concise way online that returns it into a variable as opposed to printing it in a completionHandler.

我需要查看某个URL给出的页面的HTML。如果我有这个,使用Swift获取该URL的HTML源代码的最有效和同步的方法是什么?我还没能找到一种简便的在线方法,将它返回到一个变量中,而不是在completionHandler中打印出来。

I need to manipulate the source outside of whatever call uses the URL. How is this done in Swift?

我需要在使用URL的调用之外操作源。这是如何在Swift中完成的?

5 个解决方案

#1


36  

Disclaimer : Since this is getting quite a lot of views, I just want to remind everyone that this answer here is synchronous, and will block your app if you do it on the main thread. You should always do this asynchronously (in a background thread), but the question asked for a synchronous method, so it would be out of scope to explain how to do it here.

免责声明:由于这获得了大量的视图,我只想提醒大家,这里的答案是同步的,如果你在主线程上执行的话,将会阻塞你的应用程序。您应该总是异步地(在后台线程中)执行这个操作,但是这个问题需要一个同步的方法,所以在这里解释怎么做是超出范围的。


You should probably look at the method :

你可能应该看看方法:

+ stringWithContentsOfURL:encoding:error (docs)

+ stringWithContentsOfURL:编码:错误(文档)

You would call it like this in Objective C :

你可以这样称呼Objective C:

NSString *myURLString = @"http://google.com";
NSURL *myURL = [NSURL URLWithString:myURLString];

NSError *error = nil;
NSString *myHTMLString = [NSString stringWithContentsOfURL:myURL encoding: NSUTF8StringEncoding error:&error];

if (error != nil)
{
    NSLog(@"Error : %@", error);
}
else
{
    NSLog(@"HTML : %@", myHTMLString);
}

So in Swift 3 and 4, the equivalent would be :

因此,在Swift 3和4中,等价的是:

let myURLString = "https://google.com"
guard let myURL = URL(string: myURLString) else {
    print("Error: \(myURLString) doesn't seem to be a valid URL")
    return
}

do {
    let myHTMLString = try String(contentsOf: myURL, encoding: .ascii)
    print("HTML : \(myHTMLString)")
} catch let error {
    print("Error: \(error)")
}

You might want to adapt the encoding (see the constants) depending on which encoding your page's using.

您可能希望根据页面使用的编码来调整编码(请参阅常量)。


Old answer, Swift 2.2 :

老答案,Swift 2.2:

let myURLString = "http://google.com"
guard let myURL = NSURL(string: myURLString) else {
    print("Error: \(myURLString) doesn't seem to be a valid URL")
    return
}

do {
    let myHTMLString = try String(contentsOfURL: myURL)
    print("HTML : \(myHTMLString)")
} catch let error as NSError {
    print("Error: \(error)")
}

Old answer, Swift 1.2 :

老调重弹,斯威夫特1.2:

let myURLString = "http://google.com"

if let myURL = NSURL(string: myURLString) {
    var error: NSError?
    let myHTMLString = NSString(contentsOfURL: myURL, encoding: NSUTF8StringEncoding, error: &error)

    if let error = error {
        println("Error : \(error)")
    } else {
        println("HTML : \(myHTMLString)")
    }
} else {
    println("Error: \(myURLString) doesn't seem to be a valid URL")
}

#2


5  

An updated @DCMaxx answer to Swift 2.2 :

更新后的@DCMaxx回复Swift 2.2:

let myURLString = "http://www.yahoo.com"

if let myURL = NSURL(string: myURLString) {
    var error: NSError?
    let myHTMLString = try! NSString(contentsOfURL: myURL, encoding: NSUTF8StringEncoding)

    if let error = error {
        print("Error : \(error)")
    } else {
        print("HTML : \(myHTMLString)")
    }
} else {
    print("Error: \(myURLString) doesn't  URL")
}

#3


3  

This is the way to go in Swift 2:

这是在斯威夫特2:

let myURLString = "https://duckduckgo.com/"

if let myURL = NSURL(string: myURLString) {

    do {
        let myHTMLString = try String(contentsOfURL: myURL, encoding: NSUTF8StringEncoding)
        print("HTML : \(myHTMLString)")
    } catch {
        print("Error : \(error)")
    }
} else {
    print("Error: \(myURLString) doesn't  URL")
}

Also as an extra related to previous answers:
Note that Swift 2 introduces a new error handling approach that produces much clearer code for programmers to read, it does away with complexities like & to pass in NSErrors, and it gives you greater safety by ensuring you catch all errors.

还有一个与之前的答案相关的额外内容:注意,Swift 2引入了一种新的错误处理方法,它为程序员生成了更清晰的代码供他们阅读,它消除了诸如&传入NSErrors之类的复杂性,并且通过确保捕获所有错误,它为您提供了更大的安全性。

Only use try! if you are 100% sure that the call won't fail.

只使用试试!如果你百分之百确定这个电话不会失败。

Further reading: https://www.hackingwithswift.com/new-syntax-swift-2-error-handling-try-catch

进一步阅读:https://www.hackingwithswift.com/new-syntax-swift-2-error-handling-try-catch

#4


3  

Swift 3:

斯威夫特3:

    if let url = URL(string: "https://www.google.com/trends/hottrends/atom/hourly") {
        do {
            let contents = try String(contentsOf: url)
            print(contents)
        } catch {
            // contents could not be loaded
        }
    } else {
        // the URL was bad!
    }

#5


2  

more compact functional example

更紧凑的功能示例

let myURLString = "https://google.com"

let myHTMLString = NSURL(string: myURLString)
    .flatMap { NSData(contentsOfURL: $0) }
    .flatMap { NSString(data: $0, encoding: NSASCIIStringEncoding) }

#1


36  

Disclaimer : Since this is getting quite a lot of views, I just want to remind everyone that this answer here is synchronous, and will block your app if you do it on the main thread. You should always do this asynchronously (in a background thread), but the question asked for a synchronous method, so it would be out of scope to explain how to do it here.

免责声明:由于这获得了大量的视图,我只想提醒大家,这里的答案是同步的,如果你在主线程上执行的话,将会阻塞你的应用程序。您应该总是异步地(在后台线程中)执行这个操作,但是这个问题需要一个同步的方法,所以在这里解释怎么做是超出范围的。


You should probably look at the method :

你可能应该看看方法:

+ stringWithContentsOfURL:encoding:error (docs)

+ stringWithContentsOfURL:编码:错误(文档)

You would call it like this in Objective C :

你可以这样称呼Objective C:

NSString *myURLString = @"http://google.com";
NSURL *myURL = [NSURL URLWithString:myURLString];

NSError *error = nil;
NSString *myHTMLString = [NSString stringWithContentsOfURL:myURL encoding: NSUTF8StringEncoding error:&error];

if (error != nil)
{
    NSLog(@"Error : %@", error);
}
else
{
    NSLog(@"HTML : %@", myHTMLString);
}

So in Swift 3 and 4, the equivalent would be :

因此,在Swift 3和4中,等价的是:

let myURLString = "https://google.com"
guard let myURL = URL(string: myURLString) else {
    print("Error: \(myURLString) doesn't seem to be a valid URL")
    return
}

do {
    let myHTMLString = try String(contentsOf: myURL, encoding: .ascii)
    print("HTML : \(myHTMLString)")
} catch let error {
    print("Error: \(error)")
}

You might want to adapt the encoding (see the constants) depending on which encoding your page's using.

您可能希望根据页面使用的编码来调整编码(请参阅常量)。


Old answer, Swift 2.2 :

老答案,Swift 2.2:

let myURLString = "http://google.com"
guard let myURL = NSURL(string: myURLString) else {
    print("Error: \(myURLString) doesn't seem to be a valid URL")
    return
}

do {
    let myHTMLString = try String(contentsOfURL: myURL)
    print("HTML : \(myHTMLString)")
} catch let error as NSError {
    print("Error: \(error)")
}

Old answer, Swift 1.2 :

老调重弹,斯威夫特1.2:

let myURLString = "http://google.com"

if let myURL = NSURL(string: myURLString) {
    var error: NSError?
    let myHTMLString = NSString(contentsOfURL: myURL, encoding: NSUTF8StringEncoding, error: &error)

    if let error = error {
        println("Error : \(error)")
    } else {
        println("HTML : \(myHTMLString)")
    }
} else {
    println("Error: \(myURLString) doesn't seem to be a valid URL")
}

#2


5  

An updated @DCMaxx answer to Swift 2.2 :

更新后的@DCMaxx回复Swift 2.2:

let myURLString = "http://www.yahoo.com"

if let myURL = NSURL(string: myURLString) {
    var error: NSError?
    let myHTMLString = try! NSString(contentsOfURL: myURL, encoding: NSUTF8StringEncoding)

    if let error = error {
        print("Error : \(error)")
    } else {
        print("HTML : \(myHTMLString)")
    }
} else {
    print("Error: \(myURLString) doesn't  URL")
}

#3


3  

This is the way to go in Swift 2:

这是在斯威夫特2:

let myURLString = "https://duckduckgo.com/"

if let myURL = NSURL(string: myURLString) {

    do {
        let myHTMLString = try String(contentsOfURL: myURL, encoding: NSUTF8StringEncoding)
        print("HTML : \(myHTMLString)")
    } catch {
        print("Error : \(error)")
    }
} else {
    print("Error: \(myURLString) doesn't  URL")
}

Also as an extra related to previous answers:
Note that Swift 2 introduces a new error handling approach that produces much clearer code for programmers to read, it does away with complexities like & to pass in NSErrors, and it gives you greater safety by ensuring you catch all errors.

还有一个与之前的答案相关的额外内容:注意,Swift 2引入了一种新的错误处理方法,它为程序员生成了更清晰的代码供他们阅读,它消除了诸如&传入NSErrors之类的复杂性,并且通过确保捕获所有错误,它为您提供了更大的安全性。

Only use try! if you are 100% sure that the call won't fail.

只使用试试!如果你百分之百确定这个电话不会失败。

Further reading: https://www.hackingwithswift.com/new-syntax-swift-2-error-handling-try-catch

进一步阅读:https://www.hackingwithswift.com/new-syntax-swift-2-error-handling-try-catch

#4


3  

Swift 3:

斯威夫特3:

    if let url = URL(string: "https://www.google.com/trends/hottrends/atom/hourly") {
        do {
            let contents = try String(contentsOf: url)
            print(contents)
        } catch {
            // contents could not be loaded
        }
    } else {
        // the URL was bad!
    }

#5


2  

more compact functional example

更紧凑的功能示例

let myURLString = "https://google.com"

let myHTMLString = NSURL(string: myURLString)
    .flatMap { NSData(contentsOfURL: $0) }
    .flatMap { NSString(data: $0, encoding: NSASCIIStringEncoding) }