It seems that Web::Scraper uses HTML::TreeBuilder::XPath, and HTML::TreeBuilder has an no_space_compacting option that is disabled by default, causing that module to do s/[\n\r\f\t ]+/ /g by default. At the moment I don't see a way to set arbitrary options on the parser via Web::Scraper, this is probably worth opening an issue for.

Two workarounds I see at the moment: replacing Web::Scraper with Web::Scraper::LibXML works for me:

use warnings; use strict; use Data::Dump; use Web::Scraper::LibXML; my $scraper = scraper { process '//p[contains(@class, "myClass")]', 'paragraph' => 'TEXT'; }; dd $scraper->scrape(\<<'END_HTML'); <p class="myClass">Blah Blah Blah </p> END_HTML __END__ { paragraph => "Blah\n\nBlah\n\nBlah\n" }

Or, monkey-patching Web::Scraper::build_tree:

*Web::Scraper::build_tree = sub { my($self, $html) = @_; my $t = HTML::TreeBuilder::XPath->new; $t->store_comments(1) if ($t->can('store_comments')); $t->no_space_compacting(1); $t->ignore_unknown(0); $t->parse($html); $t->eof; $t; };

In reply to Re: Preserving newlines with Web::Scraper by haukex
in thread Preserving newlines with Web::Scraper by nysus

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.