Andy Jazz
Andy Jazz

Reputation: 58103

How to get text from Web page in macOS via Swift?

How to get a string of text like this:

Simple Text Example...

from macOS' Safari page via Swift 4?

@IBOutlet weak var label: NSTextField!
@IBOutlet weak var webView: WKWebView!

override func viewDidLoad() {
    super.viewDidLoad()
    let string = "http://127.0.0.1:8080/101"
    let url = NSURL(string: string)
    let request = URLRequest(url: url! as URL)
    self.webView.load(request as URLRequest)

    //this doesn't work
    label.stringValue = webView.webFrame.frameElement.innerText
}

Here is HTML structure:

<html>
  <head></head>
    <body>
      Simple Text Example...
    </body>
</html>

UPDATE:

I've tried the following method but it has Void return...

webView.evaluateJavaScript("document.body.innerText") { (result, error) in
    if error != nil {
        print(result)
    }
}

Upvotes: 1

Views: 2544

Answers (2)

Ryan Ho
Ryan Ho

Reputation: 293

for iOS, in the webview's delegate method

func webViewDidFinishLoad(_ webView: UIWebView) {  
    var string = webView.stringByEvaluatingJavaScript(from: "document.body.textContent")
    print(string)
}

for macOS, in the webview's navigation delegate:

override func viewDidLoad() {
    webview.nagivationDelegate = self
    ...
}

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    webView.evaluateJavaScript("document.body.textContent") { (string, error) in
            print(string)
    }
}

Upvotes: 1

Jogendar Choudhary
Jogendar Choudhary

Reputation: 3494

You have to check outerhtml and innerhtml, textContent and many more tag like that:

if let htmlOuter = self.webView.stringByEvaluatingJavaScript(from: "document.body.outerHTML"){
}

Or

if let htmlInner = self.webView.stringByEvaluatingJavaScript(from: "document.body.innerHTML"){

}

Or

if let content = self.webView.stringByEvaluatingJavaScript(from: "document.body. textContent"){

}

Upvotes: 1

Related Questions