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();

In reply to getting text from HTML by IB2017

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.