AppCodah AppCodah - 1 year ago 149
iOS Question

Extract Value from html website using XPATH, Swift

I want to extract:

, from this website

You can see the text just over the donate button
51.39% of $6 Million

This is the code that i am using to TRY get that value.

let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in

if error == nil {

let urlContent = NSString(data: data!, encoding: NSASCIIStringEncoding) as NSString!

do {
// if encoding is omitted, it defaults to NSUTF8StringEncoding
let doc = try HTMLDocument(string: urlContent as String, encoding: NSUTF8StringEncoding)

// XPath queries
for element in doc.xpath("//*[@id='so_far']/text()") {

} catch let error {


The result that i am getting is:


Thank you!

Answer Source

You can't do what you are trying to achieve with XPath alone, the HTML itself contains the code:

<div class="row">
    <div class="mil"><strong id="so_far">0%</strong> <span class="light">of $6 Million</span></div>

You can see that if you run curl

It seems that the web-browser, after retrieving the HTML, subsequently executes some JavaScript which inserts the value.

However if you examine how they do this, you will see that they call this service which returns the following JSON with your answer:


So maybe just use their API?