在 Swift 中从 WKWebview 获取 HTML

Get HTML from WKWebview in Swift

我使用 WKWebView 登录到一个网站,现在我想解析该网站的 html。如何访问 swift 中的网站 html?我知道它如何用于 UIWebView 但不适用于 WKWebView。

感谢您的帮助!

如果您等到页面加载完成,您可以使用:

webView.evaluateJavaScript("document.documentElement.outerHTML.toString()", 
                           completionHandler: { (html: Any?, error: Error?) in
    print(html)
})

您还可以注入一些 javascript,您 returns 支持 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 类似于:

webkit.messageHandlers.didGetHTML.postMessage(document.documentElement.outerHTML.toString());

WKWebView

从 WKWebView

获取 HTML
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
})

将HTML设置为WKWebView

//Do not forget to extend a class from `WKNavigationDelegate`

func someFunction() {
    let wkWebView = WKWebView()

    wkWebView.loadHTMLString("<html><body></body></html>", baseURL: nil)
    wkWebView.navigationDelegate = self as? WKNavigationDelegate
}

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    //ready to be processed
}

[get/set HTML from UIWebView]

我来这里是为了在询问令牌形式 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))
    }
}

结合答案 1 和 3 对我有用:

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
   print("End loading")        
   webView.evaluateJavaScript("document.documentElement.outerHTML", completionHandler: { result, error in         
      if let datHtml = result as? String {
         print(datHtml)
         // parse datHtml here
         }
      } )
    }