iha*_*ter 9 uiwebview ios swift
我正在使用UIWebView加载网页
let urlStr = "http://duckduckgo.com"
let urlReq = NSMutableURLRequest(URL: NSURL(string: urlStr)!)
webView.loadRequest(urlReq)
Run Code Online (Sandbox Code Playgroud)
然后,当页面加载完毕后,我想访问html内容
func webViewDidFinishLoad(webView: UIWebView) {
let href = webView.stringByEvaluatingJavaScriptFromString("window.location.href")
println("window.location.href = \(href)")
let doc = webView.stringByEvaluatingJavaScriptFromString("document")
println("document = \(doc)")
}
Run Code Online (Sandbox Code Playgroud)
但是文档只返回一个空字符串(Optional("")).该window.location.href部分工作正常.我做错了什么?
nic*_*sso 19
我认为你必须像这样评估javascript:
let doc = webView.stringByEvaluatingJavaScriptFromString("document.documentElement.outerHTML")
Run Code Online (Sandbox Code Playgroud)
在这种情况下,您将获得整个HTML.
现在,当 UIWebView 被弃用时,您需要使用如下语法:
webView.evaluateJavaScript("document.documentElement.outerHTML") { (html, error) in
guard let html = html as? String else {
print(error)
return
}
// Here you have HTML of the whole page.
}
Run Code Online (Sandbox Code Playgroud)
之后,您可以创建一个像这样的函数,可以轻松地从 webView 获取 HTML:
func getHTML(_ completion: @escaping (String) -> ()) {
webView.evaluateJavaScript("document.documentElement.outerHTML") { (html, error) in
guard let html = html as? String else {
print(error)
return
}
completion(html)
}
}
getHTML { html in
// Here you have HTML string
print(html) // for example...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15028 次 |
| 最近记录: |