如何使用Swift从URL获取HTML源 [英] How To Get HTML source from URL with Swift

查看:98
本文介绍了如何使用Swift从URL获取HTML源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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的任何调用,我都需要操纵源.如何在Swift中完成?

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

推荐答案

免责声明:由于这获得了很多意见,我只想提醒所有人,这里的答案是同步的,将阻止您的应用程序如果在主线程上执行此操作.您应该始终以异步方式(在后台线程中)执行此操作,但是该问题要求使用同步方法,因此在此处解释如何执行此操作将超出范围.

您可能应该看一下方法:

You should probably look at the method :

+ stringWithContentsOfURL:encoding:error(您将在目标C中这样称呼它:

You would call it like this in 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);
}

因此在Swift 3和Swift 4中,等效项为:

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

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.

旧答案,Swift 2.2:

Old answer, 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)")
}


旧答案,Swift 1.2:


Old answer, Swift 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")
}

这篇关于如何使用Swift从URL获取HTML源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆