在 Swift 中从 WKWebview 获取 HTML [英] Get HTML from WKWebview in Swift
本文介绍了在 Swift 中从 WKWebview 获取 HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用 WKWebView 登录网站,现在我想解析网站的 html.如何快速访问网站 html?我知道它如何适用于 UIWebView 但不适用于 WKWebView.
I log into a website using WKWebView and now i would like to parse the html of the website. How can I access the websites html in swift? I know how it works for a UIWebView but not for WKWebView.
感谢您的帮助!
推荐答案
如果您等到页面加载完毕,您可以使用:
If you wait until the page has loaded you can use:
webView.evaluateJavaScript("document.documentElement.outerHTML.toString()",
completionHandler: { (html: Any?, error: Error?) in
print(html)
})
您也可以注入一些 javascript 来返回 HTML.
You could also inject some javascript that returns you back the HTML.
let script = WKUserScript(source: javascriptString, injectionTime: injectionTime, forMainFrameOnly: true)
userContentController.addUserScript(script)
self.webView.configuration.userContentController.addScriptMessageHandler(self, name: "didGetHTML")
…
func userContentController(userContentController: WKUserContentController,
didReceiveScriptMessage message: WKScriptMessage) {
if message.name == "didGetHTML" {
if let html = message.body as? String {
print(html)
}
}
}
您可以注入的 javascript 如下所示:
The javascript you could inject looks something like:
webkit.messageHandlers.didGetHTML.postMessage(document.documentElement.outerHTML.toString());
这篇关于在 Swift 中从 WKWebview 获取 HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文