我使用WKWebView登录网站,现在我想解析网站的html。如何在swift中访问网站html?我知道它如何用于UIWebView但不适用于WKWebView。
感谢您的帮助!
答案 0 :(得分:65)
如果您等到页面已加载,您可以使用:
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());
答案 1 :(得分:0)
另一个例子
wkWebView.evaluateJavaScript("document.body.innerHTML", completionHandler: { (value: Any!, error: Error!) -> Void in
if error != nil {
//Error logic
return
}
//let result = value as? String
//Main logic
})
get HTML from UIWebView
put HTML into UIWebView
put HTML into WKWebView
答案 2 :(得分:0)
我在这里是为了在从 DROPBOX 新 APIS 询问令牌后试图获得有关获得结果的线索。 (我在没有他们 SDK 的所有内容的情况下实现他们的流程) 希望能帮到人。
现在 Dropbox 使用网页作为登录名,并回调您可以处理令牌的 URL。
import WebKit
import SwiftUI
// some code from:
// https://benoitpasquier.com/create-webview-in-swiftui/
// THX pasquier!
let APP_KEY = "YOUR APP KEY"
let REDIRECT_URI = "<YOUR SITE>.dropbox_auth.php"
let DB_URL = "https://www.dropbox.com/1/oauth2/authorize?client_id=APP_KEY&token_access_type=offline&response_type=code&redirect_uri=REDIRECT_URI"
class MyWKDelegate: NSObject, WKNavigationDelegate{
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print("End loading")
webView.evaluateJavaScript("document.body.innerHTML", completionHandler: { result, error in
if let html = result as? String {
print(html)
}
})
}
}
struct WebView: UIViewRepresentable {
typealias UIViewType = WKWebView
let webView: WKWebView
func makeUIView(context: Context) -> WKWebView {
return webView
}
func updateUIView(_ uiView: WKWebView, context: Context) { }
}
class WebViewModel: ObservableObject {
let webView: WKWebView
let url: URL!
let delegate = MyWKDelegate()
init() {
webView = WKWebView(frame: .zero)
webView.navigationDelegate = delegate
let urlStr = DB_URL.replacingOccurrences(of: "APP_KEY", with: APP_KEY).replacingOccurrences(of: "REDIRECT_URI", with: REDIRECT_URI)
print(urlStr)
url = URL(string: urlStr)
loadUrl()
}
func loadUrl() {
webView.load(URLRequest(url: url))
}
}