在开发时,可能需要提取网页中的部分数据,比如标签内的标题,或者是网页的描述信息,这里利用UIWebView的Javascript可内联HTML特性抓取网页中的元素实现的。
open func stringByEvaluatingJavaScript(from script: String) -> String?
stringByEvaluatingJavaScript方法是将Javascript命令嵌入网页中,抓取数据
swift3.0:
获取html页面title的值:
let title : String = self.webView.stringByEvaluatingJavaScript(from: “document.title”)
self.webView.stringByEvaluatingJavaScript(from: “document.getElementsByTagName(‘html’)[0].innerHTML”)//打印出值为”<head></head><body></body>"
获取html页面上element的值:
let username : String = self.webView.stringByEvaluatingJavaScript(from: “document.getElementsByName(‘username’)[0].value")
给html页面上element赋值:
let loadUserNameJS = String.init(format: "document.getElementsByName('username')[0].value = '%@'", email ?? “")
//autofill the form
self.webView.stringByEvaluatingJavaScript(from: loadUserNameJS)
使用UIWebViewDelegate协议,并在你的delegate中实现如下的方法:
func webViewDidFinishLoad(_ webView: UIWebView) {
//verify view is on the login page of the site (simplified)
let requestURL : URL? = self.webView.request?.url
}
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
return true
}