I want to extract the textual parts of HTML pages (i.e. the texts that a browser normally shows). I am using the following script, however with some pages it prints out code too. The script and the url can reproduce the issue. Any idea?
use strict;
use warnings;
use LWP::Simple;
use LWP::UserAgent;
use HTML::TokeParser::Simple;
my $ua = LWP::UserAgent->new( );
my $text = do_GET_TXT("http://www.spacex.com/webcast");
print $text;
sub do_GET_TXT {
my ($url)=@_;
print "Downloading and reading HTML $url...\n";
my $response = $ua->get($url);
if ($response->is_error) {
$response->code;
}
else{
my $HTML = $response->decoded_content();
my @text;
require HTML::TokeParser::Simple;
my $p = HTML::TokeParser::Simple->new(\$HTML);
while ( my $token = $p->get_token ) {
next unless $token->is_text;
my $out = $token->as_is;
$out =~ s/^\s+/\n/;
push (@text, $out);
}
my $text = join("", @text);
#some heuristics
$text =~ s/\n+/\n/g;
$text =~ s/\n(\d+\.)\n/$1\t/g;
$text =~ s/(\(\d+\))\n/$1\t/g;
$text =~ s/([a-z]\))\n/$1\t/g;
return $text;
}
}
I obtain more or less the same using Mojo::DOM with the following:
my $dom = Mojo::DOM->new($HTML);
my $text = $dom->all_text();
A bit better gets with the following (with reduces the parsing to the body, however snippets of javascript are still to be seen...
my $dom = Mojo::DOM->new($HTML);
my $text = $dom->at('body')->all_text();
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|