0

Is there a way of retrieving div contents from a webpage in Swift or at least Obj-C? I have selected the one I wish to retrieve in the image below. It's dynamic (lottery results) so it has to be an URL.

Please advise if there is a tutorial or a method that'd allow that kind of operation. I couldn't find it for myself.

https://i.stack.imgur.com/4urh0.png

Kacper Cz
  • 504
  • 3
  • 17

1 Answers1

1

Getting the content

At first, you need to download content of that page so you can work with it as with local data. To do that, please see following post on SO, since it will give you clear idea about how to do it

I wrote multiple crawlers for different sites with objc. and swift, and for your purpose, there are more solutions, some of which are more difficult than the others, usually depending on configuration of remote server - but for what you are trying to do, I strongly suggest you to use TFHpple library.

TFHpple

Once you have it configured, what it allows you to do is to traverse parsed html / xml using XPath. From the W3C site:

XPath is a syntax for defining parts of an XML document

Basically, instead of traversing through sometime very long and dynamic tree of objects, you just define "rule" how to find it using one-line-notation and the rest is group of nodes that fit that role.

Lets say you want to find all links on the page that fits rule of class="myClass", you would use it like this:

let data = NSData(contentsOfFile: "page.html")

let document = TFHpple(HTMLData: data)
let elements = doc.search("//a[@class='myClass']")

Then, in the elements array, you can find all the results as nodes with more information and also child nodes included.

Everyone loves simplicity

If you don't not want to learn how to use XPath, there is quite simple solution. When browsing the page through Google Chrome, open developer console (Ctrl[win] / Cmd[mac] + Shift + C) and seek the tag you are interested in in "Elements" browser. Then, click right and choose copy XPath. Use that XPath in your parser, and profit :) Here is the screenshot of how it actually looks.

Good luck!

Community
  • 1
  • 1
Jiri Trecak
  • 5,092
  • 26
  • 37