Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re^3: Regexp for HTML

by marto (Cardinal)
on Jan 12, 2024 at 21:49 UTC ( [id://11156932]=note: print w/replies, xml ) Need Help??


in reply to Re^2: Regexp for HTML
in thread Regexp for HTML

Here's an example using Mojo::DOM, to make life easy, even with borked HTML. It replaces hrefs beginning with the selector ;widget=460, replacing them with the URL for this site.

#!/usr/bin/perl use strict; use warnings; use Mojo::DOM; use feature 'say'; # slurp from file, get from a live site via Mojolicious::UserAgent etc +... # hardcoded for example purposes my $html = '<p><a href="https://example.com">example.com</a></p><p><a +href=";widget=460" rel="noopener" target="_blank"><img alt="Advertise +r" class="banner" height="60" src="/images/articles/newsletters/Paper +-v4-468x60.jpg" style="display: block; margin-left: auto; margin-righ +t: auto;" width="468" /></a></p>'; my $dom = Mojo::DOM->new( $html ); for my $url ( $dom->find('a[href^=";widget=460"]')->each ){ $url->attr('href' => 'https://perlmonks.org'); } say $dom->content;

Output:

<p><a href="https://example/com">example.com</a></p><p><a href="https: +//perlmonks.org" rel="noopener" target="_blank"><img alt="Advertiser" + class="banner" height="60" src="/images/articles/newsletters/Paper-v +4-468x60.jpg" style="display: block; margin-left: auto; margin-right: + auto;" width="468"></a></p

Armed with this, it'd be trivial to have a list of widgets & their real urls, substitute the selector and static url value in the code above, looping through the list of widgets.

Update: See also Re: Batch remove URLs, or super search for more examples.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (5)
As of 2024-05-01 09:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found