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.
Thanks for your help!
A WKWebView object is a platform-native view that you use to incorporate web content seamlessly into your app's UI. A web view supports a full web-browsing experience, and presents HTML, CSS, and JavaScript content alongside your app's native views.
Loading local content WKWebView can load any HTML stored in your app bundle using its loadFileURL() method. You should provide this with a URL to some HTML file that you know is in your bundle, along with another URL that stores any other files you want to allow the web view to read. That url.
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) })
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) } } }
The javascript you could inject looks something like:
webkit.messageHandlers.didGetHTML.postMessage(document.documentElement.outerHTML.toString());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With