从 HTML WKWebView 下载图像

Download Image from HTML WKWebView

下面是我从加载到 WKWebView

中的 URL 获得的标签之一

< img id="image_id" name="imageName" src="captcha.jpg">

在 DidFinish 上是否可以将图像作为 UIImage 获取?

为了实现这一点,我使用了一些库来提供帮助。

在您使用 pod(或 carthage 或任何您喜欢的)的项目中插入以下库:

SwiftSoup

AlamofireImage

一旦您的项目设置了这些库,我们就可以开始了。

在你的故事板中,放置 2 个元素,在我的故事板中,我有一个 WKWebView,下面是一个 ImageView。 只需设置约束以确保测试时所有内容都会显示在屏幕上。

那么在代码中我们将有:

import UIKit
import WebKit
import SwiftSoup
import AlamofireImage


class ViewController: UIViewController, WKNavigationDelegate {
    @IBOutlet weak var webView: WKWebView!
    @IBOutlet weak var imageView: UIImageView!

    let url = URL(string: "https://www.google.com")
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        webView.navigationDelegate = self

        let urlReq = URLRequest(url: url!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 1)
        webView!.load(urlReq)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        webView.evaluateJavaScript("document.documentElement.outerHTML.toString()",
                                   completionHandler: { (html: Any?, error: Error?) in
                                    do{
                                        let doc: Document = try SwiftSoup.parse(html as! String)
                                        let pngs: Elements = try doc.select("img[src$=.png]")
                                        let srcsStringArray: [String?] = pngs.array().map { try? [=10=].attr("src").description }
                                        for imgs in srcsStringArray {
                                            if let imgUrl = imgs {
                                                var finalUrl = URL(string: "")
                                                if imgUrl.contains("http") {
                                                    finalUrl = URL(string: String(format: imgUrl))
                                                } else {
                                                    finalUrl = URL(string: String(format: "%@%@", (self.url?.absoluteString)!, imgUrl))
                                                }
                                                self.imageView.af_setImage(withURL: finalUrl!)
                                                print(finalUrl) //debug URL
                                            }
                                        }
                                    } catch Exception.Error(let type, let message){
                                        print(type, message)
                                    } catch {
                                        print("error")
                                    }
        })
    }
}

此示例按原样运行。

当然,您需要根据自己的需要对其进行调整,但您具备所有必要的条件。

编辑 1:

这里我只有一张图片,如果你有不止一张图片,你必须在行上妥善处理:

for imgs in srcsStringArray {...}

编辑 2:

验证码准备就绪,正在获取准确加载的图像。 在这种情况下,你不需要 Alamofire 也不需要 SwiftSoup

import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate {
    @IBOutlet weak var webView: WKWebView!
    @IBOutlet weak var imageView: UIImageView!

    let url = URL(string: "YOUR_URL")

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        webView.navigationDelegate = self

        let urlReq = URLRequest(url: url!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 1)
        webView!.load(urlReq)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {

        let str = "var c = document.createElement('canvas'); var ctx = c.getContext('2d'); ctx.drawImage(document.getElementById('captcha_id'), 100, 40); var value = c.toDataURL(); value.split(',')[1]; "

        self.webView.evaluateJavaScript(str) { (value, error) in
             if error == nil {
                 if let img = value as? String {
                      self.imageView.image = self.base64ToImage(base64: img)
                 }
             }
         }
    }

    func base64ToImage(base64: String) -> UIImage? {
        var img: UIImage = UIImage()
        if (!base64.isEmpty) {
            if let decodedData = NSData(base64Encoded: base64 , options: NSData.Base64DecodingOptions.ignoreUnknownCharacters) {
                if let decodedimage = UIImage(data: decodedData as Data) {
                    img = (decodedimage as UIImage?)!
                    return img
                }
            }
        }
        return nil
    }
}