在Swift中从WKWebview获取HTML

7xzttuei  于 2023-06-21  发布在  Swift
关注(0)|答案(4)|浏览(148)

我使用WKWebView登录到一个网站,现在我想解析网站的HTML。如何在Swift中访问HTML网站?我知道它是如何为UIWebView工作的,但不知道它是如何为WKWebView工作的。
谢谢你的帮助!

gfttwv5a

gfttwv5a1#

如果您等待页面加载,则可以用途:

webView.evaluateJavaScript("document.documentElement.outerHTML.toString()") {
    print(html)
}

你也可以注入一些javascript来返回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) {
     
    guard message.name == "didGetHTML", 
        let html = message.body as? String else { 
        return 
    }

    print(html)
}

你可以注入的javascript看起来像这样:

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

pqwbnv8z2#

Swift <->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
}

Swift <-> UIWebView(https://stackoverflow.com/a/57083045/4770877)

xxb16uws

xxb16uws3#

我在这里试图获得线索后,要求令牌形式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))
    }
}
pprl5pva

pprl5pva4#

把答案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
         }
      } )
    }

相关问题