使用WKWebKit和Swift 3获取HTML元素值 [英] Get HTML element value using WKWebKit and Swift 3
本文介绍了使用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:
- 你应该设置
navigationDelegate
而不是uiDelegate
- 由于App Transport Security,不允许对
http
地址的URL请求。如果网站支持,请使用https
或正确配置您的应用程序。 - 您错误拼写了函数名称(缺少
getElement
之后的s
) -
getElementsByClassName
返回一个数组,所以你必须选择你想要找到innerText
的元素
- You should set the
navigationDelegate
instead ofuiDelegate
- Due to App Transport Security, URL requests to
http
addresses are disallowed. Usehttps
if the website supports it or configure your app appropriately. - You misspelled the function name (missing the the
s
aftergetElement
) getElementsByClassName
returns an array so you have to pick what element you want to find theinnerText
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屋!
查看全文