Today there is increasing interest in scraping the latest data from internet. Especially textual data. There is a lot of content providing sites, such as blogs, news, forums, etc. This content is time-based (periodically updated during the time). Extracting time-based content from millions of sites is not a trivial task. The main difficulty here is that we don’t know beforehand what is the format of the HTML page that we are going to scrape.

In this post I will describe the method for extracting the time-based textual content from the blog pages in the automatic manner.

Let us look on how posts are organized in the vast majority of blogs:

<div class="post-container">
  <div class="post-1">
    <p>...</p>
    <abbr class="published entry-date">January 11, 2014</abbr>
  </div>
  <div class="post-2">
    <p>...</p>
    <abbr class="published entry-date">January 10, 2014</abbr>
  </div>
  <div class="post-3">
    <p>...</p>
    <abbr class="published entry-date">January 9, 2014</abbr>
  </div>
</div>

There are posts that consist of repeating DOM elements such as divs, spans and so on. The common feature in them is that every post contains time stamp. The time stamp might be in the beginning of the post or in the end of it, but almost always it’s a separate DOM element.

So it might be not too hard to detect the dates, using some sort of date parsing library, such as dateutil.

The dates detection process would go like this:

import datetime
from lxml import etree
from lxml.html import HTMLParser
from dateutil.parser import parse

def is_valid_date(text):
    """Based on dateutil should return True if text is valid 
       date format, and False othervise"""
    ...

def main():
    response = urllib.urlopen("http://alexeyvishnevsky.com/")
    element_tree = etree.parse(response, HTMLParser())
    date_candidates = []
    for element in element_tree.getiterator():
        text = element.xpath("text()")
        if not len(text):
            continue
        if is_valid_date(texti[0]):
            date_candidates.append(element)
    print [d.xpath("text()")[0] for d in date_candidates]

main()

Now when we have the dates, we assume that each of them is the part of the post that we need to collect, but we don’t know where does the post starts and where does it end?

Fortunately there is an efficient method to identify the posts boundaries by finding the Lowest Common Ancestor (LCA) for given dates elements in a DOM tree. Then having the dates LCA’s we can be pretty sure that its children provide the required entry points to the posts itself. Below is the picture that visualizes the idea:

Screenshot from 2014-01-19 18:31:38

Another, more complex case such as multiple post threads in the page:

Screenshot from 2014-01-19 17:57:45

All these cases are supported by the following code:

def find_lca_candidates(graph, date_candidates):
    import itertools
    lca_local_candidates = None
    lca_global_candidates = set()
    comparing_set_for_local_date_candidates = itertools.combinations(
                                                    date_candidates, 2)
    for item in comparing_set_for_local_date_candidates:
        path = graph.shortest_path(item[0].xpath, item[1].xpath)
        if not lca_local_candidates:
            lca_local_candidates = set(path)
        else:
            lca_local_candidates = lca_local_candidates.intersection(
                                                            set(path))
        if len(lca_local_candidates) == 1:
            item = lca_local_candidates.pop()
            lca_global_candidates.add(item)
            lca_local_candidates = None

    return lca_global_candidates

Where graph is the pattern.graph.Graph instance representing the HTML DOM tree. We are using here shortest_path method to find the shortest paths between the dates elements. The intersection points of these shortest paths will provide the LCA  candidates.

Then we might want to iterate through LCA’s children and extract text from them. This may be accomplished with something similar to the following actions:

def collect_posts_from_page():
    posts = []
    for lca_candidate in lca_global_candidates:
        for child in lca_candidate:
            posts.append(extract_text_from_etree(child))
    return posts

And, Yuppee!! We have got the posts!

This was a high level overview of the method. Obviously there is more optimization needed to make use of it in the production environment. Hopefully this will give some insights for those who’s interested with data mining and especially in time-based content extraction.

Thanks to my sister Natalia Vishnevsky for editing this and for the moral support.