user2174162
user2174162

Reputation: 11

How can I use Perl to extract a particular part of an HTML file

I am new to Perl, I am trying to read specific content between <div class="one"> of a HTML file.

HTML file:

<div class="one">

    <div id="two">Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.
    </div>

    <pre>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.
    </pre>

</div>

Perl Code:

my $file = "content.html";

if (-e $file) {
    open(IN, $file);
    while (<IN>) {
        chomp($line = $_);

        #print "$line\n";
    }
}

@contents = <IN>;

#check to if content in html file is in the right location,
#if content is in correct location (div class="one")
#print content in div two and three if exist

for (my $i = 0 ; $i <= $#contents ; $i++) {
    if (!$contents[$i] =~ m/^\s*<div/ && $contents[$i] =~ m/class\s*=\s*"one"/) {
        print "content in wrong location";
    }
    else {
        if ($contents[$i] =~ m/^\s*<div/) {
            print "$_";
        }
        else ($contents[$i] =~ m/^\s*<pre/) {
            print "$_";
        }
    }
}

Upvotes: 0

Views: 91

Answers (1)

mzedeler
mzedeler

Reputation: 4369

I had some success using HTML::TreeBuilder which is good at handling broken HTML.

Upvotes: 1

Related Questions