Swift Retrieve HTML data from Webview

大城市里の小女人 提交于 2019-12-06 15:25:08

问题


I am trying to obtain the data within the header of a web page that is being displayed in a UIWebView.

How do I get the raw (unformatted) HTML string from the UIWebView?

Also, I'm using iOS 9.

My question is similar to Reading HTML content from a UIWebView , but this post is from 6 years ago.


回答1:


From the top answer on the question you linked:

NSString *html = [yourWebView stringByEvaluatingJavaScriptFromString: 
                                     @"document.body.innerHTML"];

would translate into Swift:

let html = yourWebView.stringByEvaluatingJavaScriptFromString("document.body.innerHTML")

stringByEvaluatingJavaScriptFromString returns a optional, so you'd probably want to later use an if let statement:

if let page = html {
    // Do stuff with the now unwrapped "page" string
}



回答2:


swift 4:

if let html = self.webView.stringByEvaluatingJavaScript(from: "document.body.innerHTML"){

}



回答3:


Don't forgot get the html when the page render finished, if you got html too early, the result will be empty.

func webViewDidFinishLoad(webView: UIWebView) {
     print("pageDidFinished")
     if let html = webView.stringByEvaluatingJavaScriptFromString("document.documentElement.outerHTML") {
             print("html=[\(html)]")
      }

}


来源:https://stackoverflow.com/questions/33747752/swift-retrieve-html-data-from-webview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!