Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: lwp diary: day 1

by eg (Friar)
on Jan 14, 2001 at 14:42 UTC ( [id://51723]=note: print w/replies, xml ) Need Help??


in reply to lwp diary: day 1

Yeah, parsing HTML is a royal pain. All of the mixing of content and presentation. Ack. If only more people would use CSS to describe the markup semantically. For example, if the home node's had tables that looked like this:

<table class='adfu'> ... </table> ... <table class='body'> <table class='userdata'> ... </table> </table>

Then it would be dead easy to rip through the html and grab whatever section you want (not that I'm complaining -- I haven't even put in a suggestion or anythin'.) It would also make theming the site simpler as all you'd need to do is pass around a couple of style sheets.

Anyhow, I think I'm drifting Off Topic.

Given this problem, I would use LWP::Simple and HTML::Parser (which I find more generally useful than HTML::TreeBuilder, although you might also want to check out HTML::SimpleParse) What we've got to do is examine the html source and discover the meaning embedded within the page's structure. (By the way, for this reason, I think it's almost always better to work with raw rather than interpreted html.)

In this case, getting the user data from the home node turns out to be pretty easy. All you need to do is grab the data out of the sixth table in the html. Here's a start:

use LWP::Simple; use HTML::Parser; my $monk = $ARGV[0] || 'eg'; my $content = get("http://perlmonks.org/?node=$monk"); my $tables_seen = 0; my $in_user_table = 0; my $parser = HTML::Parser->new( start_h => [ sub { if ( $_[0] eq 'table' ) { $in_user_table = 1 if ++$tables_seen = += 6; } }, "tagname" ], end_h => [ sub { $in_user_table = 0 if $_[0] eq 'table'; }, "tagname" ], text_h => [ sub { print @_ if $in_user_table; }, "dtext" ], ); $parser->parse( $content ); $parser->eof;

The anonymous subs in start_h, stop_h and text_h are event handlers that are called when the parser encounters a start-element tag, a end-element tag and text, respectively. The string after the anonymous subs specifies what sort of argument the handlers receive.

What needs to be done now is to change the start, stop and text handlers to put the user data into a hash (note that for every table row, the key is in the first <td> and the value is in the second).

HTH.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://51723]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (5)
As of 2024-03-29 10:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found