如果您等到页面加载完毕,您可以使用:
webView.evaluateJavaScript("document.documentElement.outerHTML.toString()",completionHandler: { (html: Any?,error: Error?) in print(html) })
您还可以注入一些返回HTML的JavaScript.
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看起来像:
webkit.messageHandlers.didGetHTML.postMessage(document.documentElement.outerHTML.toString());