in reply to Extract Portion of HTML

my $html = '<html> --stuff-- <head> --more stuff-- </head> <body> --still more stuff-- <div class="myBody"> --all the stuff I want, which might include div tags, too-- </div> --yet more stuff-- </body> </html>'; use Web::Query qw(wq); say wq($html)->find('div.myBody')->html; # <div class="myBody"> --all the stuff I want, which might include div + tags, too-- </div> use HTML::Query 'Query'; say Query(text => $html)->query('div.myBody')->as_HTML; # <div class="myBody"> --all the stuff I want, which might include div + tags, too-- </div> use HTML::TreeBuilder qw(); say HTML::TreeBuilder->new_from_content($html)->look_down(_tag => 'div +', class => 'myBody')->as_HTML(q{}); # <div class="myBody"> --all the stuff I want, which might include div + tags, too-- </div>

Replies are listed 'Best First'.
Re^2: Extract Portion of HTML
by Corion (Patriarch) on Sep 19, 2011 at 12:27 UTC

    In addition another variant on the same theme using HTML::TreeBuilder::XPath together with HTML::Selector::XPath:

    #!perl -w use strict; my $html = '<html> --stuff-- <head> --more stuff-- </head> <body> --still more stuff-- <div class="myBody"> --all the stuff I want, which might include div tags, too-- </div> --yet more stuff-- </body> </html>'; use HTML::Selector::XPath qw(selector_to_xpath); use HTML::TreeBuilder::XPath; my $t = HTML::TreeBuilder::XPath->new_from_content($html); my $q = selector_to_xpath('div.myBody'); print $_->as_HTML for ($t->findnodes($q)); # <div class="myBody"> --all the stuff I want, which might include div + tags, too-- </div>

    The same should also be fairly simple using App::scrape, but the API currently does not allow for returning node elements (and the corresponding DOM tree), only plain text.