使用WKWebKit和Swift 3获取HTML元素值 [英] Get HTML element value using WKWebKit and Swift 3

查看:373
本文介绍了使用WKWebKit和Swift 3获取HTML元素值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用WKWebView使用首选评估Javascript swift函数获取html元素名称或值。我继续收到零。我想也许我的函数在页面加载之前触发,因此永远不会找到元素。现在只是试图按类名获取元素文本。以下是我在ViewController中的代码

Trying to get an html element name or value using preferred evaluate Javascript swift function using a WKWebView. I keep recieving nil. I think maybe my function is firing before the page is loaded, thus never finding the element. Right now just trying to get the element text by class name. Here is my code below in the ViewController

    import UIKit
    import WebKit

    class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {

        var web: WKWebView!

    override func loadView() {
        let webConfiguration = WKWebViewConfiguration()
        web = WKWebView(frame: .zero, configuration: webConfiguration)
        web.uiDelegate = self
        view = web
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let url = URL(string: "http://www.appcoda.com")
        let myRequest = URLRequest(url: url!)
        web.load(myRequest)

        web.evaluateJavaScript("document.getElementByClassName('excerpt').innerText") {(result, error) in
            if error != nil {
                    print(String(describing:result))
            }
        }
    }

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


推荐答案

你部分正确。当您拨打 evaluateJavascript 时,网站将无法完成加载。但是还有其他错误:

You are partially right. The website won't finish loading by the time you call evaluateJavascript. But there are also other errors:

  • You should set the navigationDelegate instead of uiDelegate
  • Due to App Transport Security, URL requests to http addresses are disallowed. Use https if the website supports it or configure your app appropriately.
  • You misspelled the function name (missing the the s after getElement)
  • getElementsByClassName returns an array so you have to pick what element you want to find the innerText of

试试这个:

override func viewDidLoad() {
    super.viewDidLoad()

    web = WKWebView(frame: .zero)
    web.navigationDelegate = self

    let url = URL(string: "https://www.appcoda.com")
    let myRequest = URLRequest(url: url!)
    web.load(myRequest)
}

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    web.evaluateJavaScript("document.getElementsByClassName('excerpt')[0].innerText") {(result, error) in
        guard error == nil {
            print(error!)
            return
        }

        print(String(describing: result))
    }
}

这篇关于使用WKWebKit和Swift 3获取HTML元素值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆