swift如何使用getelementsbytagname返回一个值

问题描述 投票:0回答:1

我是一名新手Swift 3.x程序员,我正在尝试将AppleScript程序转换为Swift,使用Cocoa(iMac桌面)中的WebKit从网站上删除数据。 VCgetInputByTag函数查找html标记(theTag),并假设返回该标记的文本。当我尝试使用此函数时,print(“text =(response)”)显示我想要的数据,但是我无法获得函数VCgetInputByTag来返回该字符串。请指教。

Funk Visualization(显然:字符串,如果:) - > string {

  var webTagText : String

  webTagText = ""


  webView.evaluateJavaScript("document.getElementsByTagName('\(theTag)')[\(num)].innerHTML;") {(response:Any?, error:Error?) in
     if (response != nil) {
        webTagText = response as! String
        webTagText = "\(response)"
        print("text= \(response)")
     }
     // error handling
  }



  print(webTagText)
  return webTagText

}

我使用和工作的AppleScript版本是

获取按标签输入(标签,数字) - 定义具有两个输入的函数,标签和数字

tell application "Safari" --tells AS that we are going to use Safari

    set input to do JavaScript "document.getElementsByTagName('" & theTag & "')[" & num & "].innerHTML;" in document 1

end tell

return input

结束getInputByTag

感谢所有人提前为您提供帮助。

cocoa swift3 applescript wkwebview getelementsbytagname
1个回答
0
投票

evaluateJavaScript函数是异步的,因此您不能同步从VCgetInputByTag函数返回结果字符串。你需要的是一个完成处理程序来异步返回结果。

func VCgetInputByTag(theTag : String, num : Int, completionHandler:@escaping (_ result:String)->Void){

    webView.evaluateJavaScript("document.getElementsByTagName('\(theTag)')[\(num)].innerHTML;") {(response:Any?, error:Error?) in
      if let result = response as? String{
         print("text= \(response)")
         completionHandler(result)
      }
       // error handling
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.