Screen scraping is the art of programatically extracting data from websites. If you think it's useful: it is. If you think it's difficult: it isn't. And if you think it's easy to really piss off administrators with ill-considered scripts, you're damn right. This is a tutorial on not just screen scraping, but socially responsible screen scraping. Its an amalgam of getting the data you want and the Golden Rule, and reading it is going to make the web a better place.

We're going to be doing this tutorial in Python, and will use the httplib2 and BeautifulSoup libraries to make things as easy as possible. We'll look at setting things up in a moment, but first a few words about being kind.

Websites crash. They look pretty and reliable and stable, but then a butterfly flaps its wings somewhere and they ride a handbasket straight to hell. For small websites 'hell' is a complete crash, while for bigger websites its more often sluggish performance. Either way, the butterfly flapping its wing is always an unexpected influx of traffic, and often that traffic spike is the direct result of inconsiderable screen scrapers.

For my blog, the error reports I get are all generated by overzealous webcrawlers from search engines (perhaps the most ubiquitous specie of screenscraper). Early on, I would routinely be assaulted by a small research web crawler whose owner was nigh impossible to contact. Not infrequently it would crash things by initiating more http requests than my small vps could handle. The programmers who wrote the scraper weren't being considerate, and it was causing problems.

This brings us to my single rule for socially responsible screen scraping: screen scraper traffic should be indistinguishable from human traffic. By following this rule we avoid placing undue stress on the websites we are scraping, and as an added bonus we'll avoid any attempts to throttle or prevent screen scraping1. We'll use a couple of guidelines to help our scripts feign humanity:

Cache feverently. Especially when you're scraping a relatively small amount of data (and your computer has a lot of memory to store in), you should save and reuse results as much as possible.

Stagger http requests. Although it'll speed things up for you to make all the http requests in parallel, it won't be appreciated. However, even if you make the requests sequentially it can end up being a fairly large hit. Instead, space your requests out by a small period of time. Several seconds between each request assures that you won't be causing problems.

Take only what you need. When screen scraping it's tempting to just grab everything, downloading more and more pages just because they are there. But its a waste of their bandwidth and your time, so make a list of the data you want to extract and stick to it.

Now, armed with those three guidelines, lets get started screen scraping.

Setup Libraries

First we need to install the httplib2 and BeautifulSoup libraries. The easiest way to do this is to use easy_install.

sudo easy_install BeautifulSoup
sudo easy_install httplib2

If you don't have easy_install installed, then you'll need to download them from their project pages at httplib2 and BeautifulSoup.

Choosing a Scraping Target

Now lets get scraping. We're going to start small and grow a simple and considerate library for scraping HackerNews. The first step is to consider what data we want to extract. The web interface to HackerNews looks like this:

Thus, from loading only the frontpage we can extract a lot of data about each story: the title, the link, the social score, the poster, when it was posted, and the number of comments. There are 30 hits displayed on each page, so we'll be able to gather a fair bit of data with only retrieving one page.

The Simplest Case

With `httplib2 and BeautifulSoup its quick and easy to extract the data we need from HackerNews. Simple enough to just throw a few commands into the interpreter:

The bit with titles is necessarily confusing. The titles css class is sued for both the td tags that contain the number of the item (for example 1. or 15.), and for the td tags that contain the a tags with the title of the story and its link. However, we only want the later kind, so we filter out the td tags without any children tags. We're also excluding the last result from that filtered list. That's because the last one contains the More link to view the next 30 results, and is not actually a story itself.

So we're pretty close to what we want, but the data isn't in a very accessible format yet. Lets try to finagle it into something usable. Right now each story is a 2-tuple of Tag objects:

So, we've figured out how to grab everything except how long ago the story was posted. Thus far we were using the findChildren method to navigate the tag tree, but there is also the contents attribute, which allows access to both tags and strings.

There is only one slight flaw here, and that is when the number of comments for a story is zero, it has discuss displayed instead of 0 comments. We can fix that up pretty quickly, and the improved function looks like this:

Looking at that data, of the thirty stories there are only twenty-one submitters, and mqt has the highest PosterRank score. Certainly you could think of (much) more exciting things to do with the data, but the dictionary format makes it easy to play to your hearts content.

Caching, Caching, Caching

Now let's backtrack a bit and look at how we can be more considerate about fetching pages. Our first page fetching looked like this:

That doesn't really improve things, but it opens the door for us to add some caching to our fetches.

importhttplib2,timefromBeautifulSoupimportBeautifulSoupSCRAPING_CONN=httplib2.Http(".cache")SCRAPING_CACHE_FOR=60*15# cache for 15 minutesSCRAPING_CACHE={}deffetch(url,method="GET"):key=(url,method)now=time.time()ifSCRAPING_CACHE.has_key(key):data,cached_at=SCRAPING_CACHE(key)ifnow-cached_at<SCRAPING_CACHE_FOR:returndatadata=SCRAPING_CONN.request(url,method)SCRAPING_CACHE[key]=(data,now)returndata# Fetch the page.page=fetch("http://news.ycombinator.com/")# Fetch the page again, but use cached copy.page=fetch("http://news.ycombinator.com/")

Now we'll retrieve each individual page at most once every fifteen minutes, which will help cut down on us stressing the server2.

Staggering Requests

Now, lets say we wanted to fetch the article that each story refers to. Using our new fetch function thats pretty easy to do:

>>> pages=[fetch(x['link'])forxinstories]

Now, in this situation each of the stories will be on a different server, so staggering the request apart won't be terriably important, but lets imagine for a moment that they were all on the same server (for example, if we wanted to fetch the comments page for each story). We can modify the fetch function to be more considerate about its requests:

With that modification it'll return cached data as quickly as possible, but will stagger any new requests. This is still a bit rough though, we really want to stagger requests by domain, not to stagger every single request.

Now we have a convenient and compassionate fetch function written. Now we can write the same barbaric code as before:

>>> pages=[fetch(x['link'])forxinstories]

And its no longer going to pound any servers, even if all the stories are located on the same domain. Instead it'll sequentially download the stories, and will respect the 1.1 second pause between requests to the same domain. This could be improved upon in a number of ways (run the downloads in parallel, etc), but we've created a nice foundation of a tool that we can use recklessly without inflicting our recklessness upon others.

Pulling the Code Together

Pulling the code that we've written together we can write a simple and considerate script for displaying the top stories--sorted by number of comments--on HackerNews every five minutes, but that will only fetch the page at most once every fifteen minutes.

Sidenote about Httplib2

You probably noticed early on that we're doing something cache related when we initialize our httplib2.Http object that we're using for requests. The initialization code looks like this:

importhttplib2SCRAPING_CONN=httplib2.Http(".cache")

Whats happening there is that httplib2 understands http caching directives, and will locally cache and reuse the cached data if the server has the appropriate caching directives. Thus there is an additional layer of caching underneath the caching layer that we wrote, and makes this stack even a bit friendler than what we've put together ourselves.

Ending Thoughts

I feel pretty strongly that screen scraping someone's website is like visiting their home: its not that hard to be considerate and polite, and the host will really appreciate it. Hopefully this tutorial has given you some thoughts about other even more effective ways for reducing the load caused by your screen scraping. Let me know if I've made any mistakes, and I'd be glad to hear any comments and thoughts on how you screen scrape responsibly.

This isn't--in any sense--an evil thing to do. The reason people throttle screen scraping is to deal with inconsiderable scrapers who consume inordinate amounts of bandwidth and other finite resources (cpu load, etc).↩

However, keep in mind when you're using local memory to store data that instances of the Python interpreter cannot share that data, so if your web server was running a script like this across several interpreter instances then it would retrieve the page once every fifteen minutes (if you were constantly trying to fetch the data) for each interpreter instance.

In such situations you'd be better off using something like memcached which would allow the instances to share their caches.↩