我试图使用SwiftSoup来刮一些HTML。此示例基于SwiftSoup github文档,工作良好的…
func scrape() throws {
do {
let htmlFromSomeSource = "<html><body><p class="nerp">HerpDerp</p><p class="narf">HoopDoop</p>"
let doc = try! SwiftSoup.parse(htmlFromSomeSource)
let tag = try! doc.select("p").first()!
let tagClass = try! tag.attr("class")
} catch {
print("oh dang")
throw Abort(.notFound)
}
print(tagClass)
}…直到我弄乱了选择器或属性目标,这时一切都崩溃了,这要归功于隐式展开的选项(我认为这只是让更聪明的人开始使用的快速和肮脏的代码)。那样做/抓住似乎一点帮助都没有。
那么正确的方法是什么?这是汇编..。
print("is there a doc?")
guard let doc = try? SwiftSoup.parse(response.body.description) else {
print("no doc")
throw Abort(.notFound)
}
print("should halt because there's no img")
guard let tag = try? doc.select("img").first()! else {
print("no paragraph tag")
throw Abort(.notFound)
}
print("should halt because there's no src")
guard let tagClass = try? tag.attr("src") else {
print("no src")
throw Abort(.notFound)
}..。但是,如果我弄乱了选择器或属性,它就会崩溃,“意外地在打开可选值时发现为零”(在“有文档吗?”之后)。我以为警卫会在遇到零的时候阻止这个过程?(如果我改了“试一试?”若要“尝试”,编译器抱怨“条件绑定的初始化程序必须具有可选类型”…)
发布于 2018-04-27 16:20:07
如果将函数声明为throws,则不需要函数内的do - catch块。只需在try之后删除块和感叹号就可以将错误传递给调用方函数。
func scrape() throws { // add a return type
let htmlFromSomeSource = "<html><body><p class="nerp">HerpDerp</p><p class="narf">HoopDoop</p>"
let doc = try SwiftSoup.parse(htmlFromSomeSource)
guard let tag = try doc.select("p").first() else { throw Abort(.notFound) }
let tagClass = try tag.attr("class")
// return something
}https://stackoverflow.com/questions/50066295
复制相似问题