Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: Trying to Insert Alt Tags Programmatically

by Anonymous Monk
on Apr 02, 2011 at 15:05 UTC ( #897098=note: print w/replies, xml ) Need Help??


in reply to Trying to Insert Alt Tags Programmatically

Here's what I have:

Nice fragment :) here is a complete program

#!/usr/bin/perl -- use strict; use warnings; use HTML::TreeBuilder; Main(@ARGV); exit(0); sub Main { my $html = '<html><body> <img src="0" alt="0"> <img src="1" alt="1"> <img src="2" alt="2"> <img src="3" alt=""> <img src="4"> <img src="5"> </body></html>'; my $tree = HTML::TreeBuilder->new(); $tree->parse($html); local $\ = $/; print $_->as_HTML for $tree->look_down( qw' _tag img ', sub { not defined $_[0]->attr('alt') } ); print '---'; print $_->as_HTML for $tree->look_down( qw' _tag img ', sub { not length $_[0]->attr('alt') } ); print '---'; $_->attr( alt => MAlt($_) ) for $tree->look_down( qw' _tag img ', sub { not length $_[0]->attr('alt') } ); print $_->as_HTML for $tree->look_down(qw' _tag img '); } ## end sub Main sub MAlt { '!' . $_[0]->attr('src') } __END__ <img src="4" /> <img src="5" /> --- <img alt="" src="3" /> <img src="4" /> <img src="5" /> --- <img alt="0" src="0" /> <img alt="1" src="1" /> <img alt="2" src="2" /> <img alt="!3" src="3" /> <img alt="!4" src="4" /> <img alt="!5" src="5" />
Alternatively, try HTML::TreeBuilder::XPath
#!/usr/bin/perl -- use strict; use warnings; use HTML::TreeBuilder::XPath; Main(@ARGV); exit(0); sub Main { my $html = '<html><body> <img src="0" alt="0"> <img src="1" alt="1"> <img src="2" alt="2"> <img src="3" alt=""> <img src="4"> <img src="5"> </body></html>'; my $tree = HTML::TreeBuilder::XPath->new(); $tree->parse($html); local $\ = $/; print $_->as_HTML for $tree->findnodes('//img[not(@alt)]'); print '---'; print $_->as_HTML for $tree->findnodes('//img[not(string-length(@a +lt))]'); print '---'; $_->attr( alt => MAlt($_) ) for $tree->findnodes('//img[not(string-length(@alt))]'); print $_->as_HTML for $tree->findnodes('//img'); } ## end sub Main sub MAlt { '!' . $_[0]->attr('src') } __END__

Replies are listed 'Best First'.
Re^2: Trying to Insert Alt Tags Programmatically
by socrtwo (Sexton) on Apr 02, 2011 at 15:54 UTC
    Wow, thanks. I will try them :-).

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://897098]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (5)
As of 2022-10-05 08:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My preferred way to holiday/vacation is:











    Results (21 votes). Check out past polls.

    Notices?