views:

1227

answers:

12

How does one intelligently parse data returned by search results on a page?

For example, lets say that I would like to create a web service that searches for online books by parsing the search results of many book providers' websites. I could get the raw HTML data of the page, and do some regexs to make the data work for my web service, but if any of the websites change the formatting of the pages, my code breaks!

RSS is indeed a marvelous option, but many sites don't have an XML/JSON based search.

Are there any kits out there that help disseminate information on pages automatically? A crazy idea would be to have a fuzzy AI module recognize patterns on a search results page, and parse the results accordingly...

+1  A: 

Without a fixed HTML structure to parse, I would hate to maintain regular expressions for finding data. You might have more luck parsing the HTML through a proper parser that builds the tree. Then select elements ... that would be more maintainable.

Obviously the best way is some XML output from the engine with a fixed markup that you can parse and validate. I would think that a HTML parsing library with some 'in the dark' probing of the produced tree would be simpler to maintain than regular expressions.

This way, you just have to check on <a href="blah" class="cache_link">... turning into <a href="blah" class="cache_result">... or whatever.

Bottom line, grepping specific elements with regexp would be grim. A better approach is to build a DOM like model of the page and look for 'anchors' to character data in the tags.

Or send an email to the site stating a case for a XML API ... you might get hired!

Aiden Bell
Regular expressions can be maintainable if done right. Some flavors allow embedded comments, which can help a LOT. You can also use capturing groups and lazy quantifiers to match structural elements before and after, and capture the data (with lazy quantifier) in between. Behaves a lot like DOM or tree parsing, but doesn't need clean XML.
BobMcGee
+1  A: 

Have you looked into using a html manipulation library? Ruby has some pretty nice ones. eg hpricot

With a good library you could specify the parts of the page you want using CSS selectors or xpath. These would be a good deal more robust than using regexps.

Example from hpricot wiki:

 doc = Hpricot(open("qwantz.html"))
 (doc/'div img[@src^="http://www.qwantz.com/comics/"]')
   #=> Elements[...]

I am sure you could find a library that does similar things in .NET or Python, etc.

BaroqueBobcat
+3  A: 

You don't say what language you're using. In Java land you can use TagSoup and XPath to help minimise the pain. There's an example from this blog (of course the XPath can get a lot more complicated as your needs dictate):

URL url = new URL("http://example.com");
SAXBuilder builder = new SAXBuilder("org.ccil.cowan.tagsoup.Parser"); // build a JDOM tree from a SAX stream provided by tagsoup
Document doc = builder.build(url);
JDOMXPath titlePath = new JDOMXPath("/h:html/h:head/h:title");
titlePath.addNamespace("h","http://www.w3.org/1999/xhtml");
String title = ((Element)titlePath.selectSingleNode(doc)).getText();
System.out.println("Title is "+title);

I'd recommend externalising the XPath expressions so you have some measure of protection if the site changes.

Here's an example XPath I'm definitely not using to screenscrape this site. No way, not me:

"//h:div[contains(@class,'question-summary')]/h:div[@class='summary']//h:h3"
Rich Seller
A: 

If you can use something like Tag Soup, that'd be a place to start. Then you could treat the page like an XML API, kinda.

It has a Java and C++ implementation, might work!

Nick Veys
+1  A: 

Unfortunately 'scraping' is the most common solution, as you said attempting to parse HTML from websites. You could detect structural changes to the page and flag an alert for you to fix, so a change at their end doesn't result in bum data. Until the semantic web is a reality, that's pretty much the only way to guarantee a large dataset.

Alternatively you can stick to small datasets provided by APIs. Yahoo are working very hard to provide searchable data through APIs (see YDN), I think the Amazon API opens up a lot of book data, etc etc.

Hope that helps a little bit!

EDIT: And if you're using PHP I'd recommend SimpleHTMLDOM

Al
+1  A: 

You haven't mentioned which technology stack you're using. If you're parsing HTML, I'd use a parsing library:

There are also webservices that do exactly what you're saying - commercial and free. They scrape sites and offer webservice interfaces.

And a generic webservice that offers some screen scraping is Yahoo Pipes. previous stackoverflow question on that

Jon Galloway
+2  A: 

It isn't foolproof but you may want to look at a parser such as Beautiful Soup It won't magically find the same info if the layout changes but it's a lot easier then writing complex regular expressions. Note this is a python module.

Jared
+6  A: 

I've done some of this recently, and here are my experiences.

There are three basic approaches:

  1. Regular Expressions.
    • Most flexible, easiest to use with loosely-structured info and changing formats.
    • Harder to do structural/tag analysis, but easier to do text matching.
    • Built in validation of data formatting.
    • Harder to maintain than others, b/c you have to write a regular expression for each pattern you want to use to extract/transform the document
    • Generally slower than 2 and 3.
    • Works well for lists of similarly-formatted items
    • A good regex development/testing tool and some sample pages will help. I've got good things to say about RegexBuddy here. Try their demo.
    • I've had the most success with this. The flexibility lets you work with nasty, brutish, in-the-wild HTML code.
  2. Convert HTML to XHTML and use XML extraction tools. Clean up HTML, convert it to legal XHTML, and use XPath/XQuery/ X-whatever to query it as XML data.
    • Tools: TagSoup, HTMLTidy, etc
    • Quality of HTML-to-XHML conversion is VERY important, and highly variable.
    • Best solution if data you want is structured by the HTML layout and tags (data in HTML tables, lists, DIV/SPAN groups, etc)
    • Most suitable for getting link structures, nested tables, images, lists, and so forth
    • Should be faster than option 1, but slower than option 3.
    • Works well if content formatting changes/is variable, but document structure/layout does not.
    • If the data isn't structured by HTML tags, you're in trouble.
    • Can be used with option 1.
  3. Parser generator (ANTLR, etc) -- create a grammar for parsing & analyzing the page.
    • I have not tried this because it was not suitable for my (messy) pages
    • Most suitable if HTML structure is highly structured, very constant, regular, and never changes.
    • Use this if there are easy-to-describe patterns in the document, but they don't involve HTML tags and involve recursion or complex behaviors
    • Does not require XHTML input
    • FASTEST throughput, generally
    • Big learning curve, but easier to maintain

I've tinkered with web harvest for option 2, but I find their syntax to be kind of weird. Mix of XML and some pseudo-Java scripting language. If you like Java, and like XML-style data extraction (XPath, XQuery) that might be the ticket for you.


Edit: if you use regular expressions, make sure you use a library with lazy quantifiers and capturing groups! PHP's older regex libraries lack these, and they're indispensable for matching data between open/close tags in HTML.

BobMcGee
+1  A: 

Try googling for screen scraping + the language you prefer. I know several options for python, you may find the equivalent for your preferred language:

  • Beatiful Soup
  • mechanize: similar to perl WWW:Mechanize. Gives you a browser like object to ineract with web pages
  • lxml: python binding to libwww
  • scrapemark: uses templates to scrape pieces of pages
  • pyquery: allows you to make jQuery queries in xml/xhtml documents
  • scrapy: an high level scraping and web crawling framework for writing spiders to crawl and parse web pages

Depending on the website to scrape you may need to use one or more of the approaches above.

filippo
A: 

Fair enough, I am going to use The Tag soup method as recommended.

As a followup question - how on earth do those big scraper-type sites do it? I have seen a job search engine (e.g. indeed.com) that scans thousands of sites! Is that thousands of regexes? Its next to impossible...

+1  A: 

Parsley at http://www.parselets.com looks pretty slick.

It lets you define 'parslets' using JSON what you're define what to look for on the page, and it then parses that data out for you.

Alex Black
A: 

As others have said, you can use an HTML parser that builds a DOM representation and query it with XPath/XQuery. I found a very interesting article here: Java theory and practice: Screen-scraping with XQuery - http://www.ibm.com/developerworks/xml/library/j-jtp03225.html

cdarwin