The transit demo site I'm building uses data from several websites - such as the Port Authority's press page. Unfortunately, most sites aren't designed for easy parsing; usually data is only available as HTML. So I need to parse HTML to uncover useful information, and if you've ever looked at the source of an average web page, writing a parser from scratch is a challenging task.
Enter the jsoup library. This programming interface exposes the structure of a HTML document in a way that can be queried, traversed and even altered by Java programs. I had previously used it to clean out HTML tags from user-submitted content, but recently have been taking advantage of its powerful query engine, which is similar to the way jQuery selectors operate.
Let's say I'm parsing some markup that repeats for different stories:
I would want to parse this by first finding all of the stories using the
In the real world, sites don't usually have markup this nice. Often they don't even have a containing element around the markup I'm interested in. For example the MTA site has headlines all in the same containing element, and stories are delimited only by the archaic
Using the jsoup library, it is possible to extract data from even the messiest websites with much less effort than would be required to write a parser using the standard Java SDK.
Enter the jsoup library. This programming interface exposes the structure of a HTML document in a way that can be queried, traversed and even altered by Java programs. I had previously used it to clean out HTML tags from user-submitted content, but recently have been taking advantage of its powerful query engine, which is similar to the way jQuery selectors operate.
Let's say I'm parsing some markup that repeats for different stories:
I would want to parse this by first finding all of the stories using the
<div class="story">
element, and then for each story, query for interesting bits of data. For instance I might want to know the headline, a short blurb of text and the URL of the story:In the real world, sites don't usually have markup this nice. Often they don't even have a containing element around the markup I'm interested in. For example the MTA site has headlines all in the same containing element, and stories are delimited only by the archaic
<hr/>
tag. In this case, I query for the containing element and loop through all of its children, noting interesting tags along the way. When I hit a boundary, I evaluate the tags I found to extract the news story information.Using the jsoup library, it is possible to extract data from even the messiest websites with much less effort than would be required to write a parser using the standard Java SDK.
Comments
Post a Comment