Writing a Windows Phone Website Scraper Application
Join the DZone community and get the full member experience.Join For Free
in this tutorial i will explain how you write a wp7 application using
the htmlagility pack in order to use information scraped from a
website scraping is the act of retrieving information from a website page. an act by some considered stealing, by others borrowing. let’s leave that debate to the others. in this post i will show how easy it is to scrape content from a website so that you can (re)use it in your windows phone 7 application. as it is, this information will for the most part also work in other, non wp7, projects of course.
sometimes website scraping is the only means available to consume certain information from a website. if the website doesn’t have some publicly available api or web service you can use you’re pretty much left with scraping, whether you like it or not.
now before reading on, it is extremely important to understand that there are legal issues concerning scraping: basically, as far as i understand it, you’re only allowed to use scraped data if you have clearance to do so by the website owner (i.e. the one that ‘owns’ the data).
to get started, we will first need the html agility pack (hap) which is a very thorough html parser (read all about it here ). the nice thing about hap is that it also supports xpath queries and linq to objects, making it actually fun (in a geeky way) to perform webscraping in c#. unfortunately, currently ‘hap for wp7’ doesn’t support xpath queries so we’ll use linq to objects for the remainder of this tutorial.
for some nice demos of what can be done with hap, make sure to check out the following tutorial .
when you download hap from codeplex, you will still need to build the wp7 dll manually. following post describes the steps needed to do this. for the lazy people amongst us, here you will find the compiled dll, based on the hap version of february 2012 (make sure to ‘unblock’ the dll if you downloaded it from this site: rightclick the file, choose properties and then click ‘unblock’).
add reference to hap in wp7
next we need to add a reference to the hap dll in order to use all the sweetness it contains. rightclick in your solution explorer on the references folder and choose add reference.
next point to the downloaded or compiled htmlagilitypack.dll file and choose add.
finally add a using statement and we are all set to go:
download page to scrape
we use the loadasync method from the static hap class htmlweb in order to download and parse our html file. we provide the url to download, as well as the callback method once the file is downloaded and processed by hap:
next we define the callback method in which we immediately check if the download went well. once that is done, we can start querying our parsed html document:
alternatives to downloading pages directly
as a side note, you might as well use the wp7 webclient.downloadstringasync method to download the html. afterwards you can then feed the downloaded string (or a string you retrieved through some other obscure manner) to hap using the loadhtml() method:
discovering the page layout
for the purpose of this demo, we would like to retrieve the url to latest xkcd.com joke image. in order to do this, the best way is to open your browser and open the developer’s tool by hitting the f12 key (works for me in chrome and ie9). i prefer to use chrome for this because of the simple fact that the currently selected element is highlighted on the page itself, making it easier to rapidly drill down to the element you need.
to rapidly view the position of a specific element inside the html dom, simply right click the element on the page and choose “inspect element”. so we right click the image and choose “inspect element”:
using the developer tool you now have to look for the element(s)
and/or attributes needed. once correctly identified the needed element,
you need to find the most straightforward way to retrieve to element in
- if the html has abundant div and/or other elements with unique id’s, it is simply a matter of finding that specific element by filtering out to the unique id.
- if the element has no unique identifier and is part of a group of equal elements you will need to iterate over all these elements and do some manual comparisons using for example regular expression; or hardcode the exact position (e.g. retrieve the 3th img element from a given node).
note, at the bottom of the developer tools you’ll also notice the full ‘path’ of the element, which can be handy if you’re getting lost in more advanced (or crappy) pages.
to be honest, the ‘hardest part’ in my opinion is identifying the correct to the wanted element.
using linq-to-objects to get the goodies
once we have identified the correct way of retrieving the element (or a certain attribute value of that element) it is time to start writing the necessary linq code. the basic principles are explained very clearly in this blog , so i’ll immediately dive into some more ‘hardcore’ *ahem * html.
for this demo we need the value of the “src” attribute of the img-element, inside the uniquely named div-element with id “comic”
first we’ll try to ‘capture’ the unique div, if we don’t find that one we can be pretty certain that some error occurred (e.g. our url is wrong, the site has changed its html, etc.):
so here we capture all the child nodes of the document that are div-elements whose “id” attribute equals “comic”. notice that a new ienumerable collection is returned: we can feed this collection to a new query or iterate over this collection with, for example, a foreach loop.
because we actually know that there will be only one element, or none at all, we will change our query to:
by using firstordefault() we can then check if the correct element was found or not (it will be null if not found), without having to cope with possible exceptions:
once inside the if-braces, we can be fairly we’ll find the desired image url.
because we know that inside the comic-div there will be only one element of the img-kind we can retrieve the value of its attributes using the following statement:
the element() method returns the single element of the “img” type. next we we retrieve the value of the “src” attribute of the -element.
it should be noted that the slightest mistake in your queries can result in some exception being thrown; make it a practice to catch these (otherwise your wp7 will simple quit without any notification should an hap exception occur).
using element and elements
depending on your preference, there’s several ways to retrieve the data you need. for example, if we are 100% certain that the page will have the html layout we need, we can drill down to the needed value using the element/elements methods, as follows.
- you use element(string type) if you are certain that the current node will have one and only one child element of the given type , that is passed as parameter.
- you use elements(string type) to retrieve all the child nodes of the current node of a given type.
in order to retrieve our image url, we could open the developer tool and note the unique path to it on the bottom of the window:
it’s now a matter of translating this path to the correct fluent method chain (is that a correct word?) , resulting in the following:
in fact, we could even hardcore this more (not always recommended). we know that we need the second div element of the body, and inside that div we again need the second div-element. se we could write and thus skip the need for specifying the filters:
note: i can’t really proclaim to be a skilled linq writer, so if any of these steps can be done more quickly, don’t hesitate to mention so.
cherry on the pie: show the image
to show that this works, suppose we have the following , very empty, wp7 xaml page on which we wish to load the joke:
all that needs to be done is assign the retrieved url as a new source to the image control,named jokeimg:
that’s all folks!
Published at DZone with permission of Tim Dams, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.