1

I have run into a challenge with getting certain data from a website for our Swift 5.0-based iOS App.

First we fill out and submit a form in the background and then the website displays some data that we would like to put into separate values in our App (for later use in labels, tableView etc.

We get the inner HTML as a string like this:

webView.evaluateJavaScript("document.getElementsByTagName('html')[0].innerHTML")

The resulting string contains all the data I need, but I have trouble extracting it.

The values I'm looking for are arranged like this (data I want to extract marked "keyName" and "valueName" (following classes "key" and "value"):

<div class="box">
        <div class="notrequired keyvalue singleDouble">
            <span class="key">keyName:</span>
            <span class="value">valueName</span>
        </div>          
        <div class="notrequired keyvalue singleDouble">
            <span class="key">keyName:</span>
            <span class="value">valueName</span>
        </div>
        <div class="notrequired keyvalue singleDouble">
            <span class="key">keyName:</span>
            <span class="value">valueName</span>
        </div>
        <div class="notrequired keyvalue singleDouble">
            <span class="key">keyName:</span>
            <span class="value">valueName</span>
        </div>
</div>

Does anybody have an idea as to how I can get the the KEY and VALUE?

Thanks.

  • BTW, the keyNames are always the same and unique, so I'm just looking to get the "valueName" following a predefined "keyName". – Emil Sørensen Aug 24 '20 at 09:04

2 Answers2

1

you can check this library SwiftSoup and this answer can be helpful How to parse html table data to array of string in swift?

Hope it will help. Looks like this is your case!

1

It's quite easy with Regular Expression capturing the string between class="value"> and <, htmlString represents the extracted HTML string. The result is an array of strings

let regex = try! NSRegularExpression(pattern: "class=\"value\">([^<]+)<")
let values = regex.matches(in: htmlString, range: NSRange(htmlString.startIndex..., in: htmlString))
    .map{ String(htmlString[Range($0.range(at:1), in: htmlString)!]) }

print(values)
vadian
  • 274,689
  • 30
  • 353
  • 361