Search code examples
htmlperlhrefread-write

Parse html using Perl


I have the following html-

<a href="http://address.com">John</a>: I really <b>love</b> <b>soccer</b>;

I want to parse it into a csv where I would have

name = John

comment = I really love soccer.

key words = love, soccer

in the console app, any help is much appreciated.


Solution

  • Here is an example how to do parsing with HTML::TreeBuilder:

    use HTML::TreeBuilder;
    
    my $html = HTML::TreeBuilder->new_from_content(<<END_HTML);
    <a href="http://address.com">John</a>: I really <b>love</b> <b>soccer</b>;
    END_HTML
    
    my $name     = $html->find('a')->as_text;               # "John"
    my @keywords = map { $_->as_text } $html->find('b');    # "love", "soccer"
    my $comment  = $html->as_text;                          # "John: I really love soccer; "
    

    Cleaning up $comment is left as an exercise.