mldvx4 has asked for the wisdom of the Perl Monks concerning the following question:

I'm getting a lot done with HTML::TreeBuilder / HTML::Element but am now puzzled as to how to merge two anchor elements. I'd like to merge two adjacent anchor elements, if they are found in a table cell, such that the text of both is concatenated but the href from the second one is retained and the href from the first one discarded. (If there are other attributes, I don't mind a way that allows me to keep them.)

What I have so far is below. The line with N= shows that I, can in principle get the right data. But I can't get splice_content() to work in this situation. Is there a better or easier way to merge two adjacent <a> elements? Or how do I fix this way?

#!/usr/bin/perl use warnings; use strict; use HTML::TreeBuilder; my $root = HTML::TreeBuilder->new; $root->implicit_tags(0); $root->parse_file( \*DATA ); foreach my $td ( $root->look_down( _tag => 'td' ) ) { my $td2 = $td->clone(); my $merge = HTML::TreeBuilder->new; $merge->implicit_tags(0); next unless ( scalar $td2->content_list > 2 ); my @anchor=(); my $href=''; foreach my $a ( $td2->look_down( _tag => 'a' ) ) { push( @anchor, $a->as_trimmed_text() ); $href = $a->attr('href'); } print qq(N=$href\t),join(' ', @anchor),qq(\n); $merge->unshift_content( [ 'a', {'href'=>$href}, @anchor ], ); $td->splice_content( 1, 2, $merge ); $merge->delete(); } print $root->as_HTML( undef, " " ); $root->delete(); exit( 0 ); __DATA__ <table> <tr> <td><a href="/a.shtml">OK</a></td> <td>OK, too 1</td> <td><a href="/parta1.shtml">parta1</a> <a href="/parta2.shtml">parta2</a></td> </tr> <tr> <td><a href="/c.shtml">OK</a></td> <td>OK, too 2</td> <td><a href="/partb1.shtml">partb1</a> <a href="/partb2.shtml">partb2</a></td> </tr> </table>

PS the next unless clause is not fussy about what kind of elements. Is there a way to have it count just anchors?

Replies are listed 'Best First'.
Re: Merging two anchors with HTML::TreeBuilder
by Anonymous Monk on May 10, 2016 at 03:07 UTC

    forget about "splice", detach/delete/remove the tag you dont want, and push_content to the tag you want, or replace it with a new tag (replace_with )

      HTML::TreeBuilder::XPath with htmltreexpather.pl makes it easier to find what you want, like the second link in each tablecell
      use HTML::TreeBuilder::XPath; #~ my $root = HTML::TreeBuilder->new; my $root = HTML::TreeBuilder::XPath->new; for my $secondlink ( $root->findnodes( '//td/a[2]' ) ){ my $td = $secondlink->parent; my $newtext = $td->as_trimmed_text ; $secondlink->delete_content; $secondlink->push_content( $newtext ) ; $secondlink->detach; $td->delete_content; $td->push_content( $secondlink ); }

        Thanks, both. I've gone with the HTML::TreeBuilder::XPath option.