perl - 我应该如何使用 Mojo::UserAgent 处理 HTML META 标签?

标签 perl mojolicious mojo-useragent

我不得不使用一些配置错误的 Web 服务器,因此我开始处理 HTML 元标记以将信息反馈回 Web 用户代理对象。我在 Mojolicious 中尝试了多种方法来做到这一点并决定在响应中寻找“完成”事件。我的目标是让代码的其余部分几乎不可见,因此该过程甚至不知道发生了这种情况。

尽管如此,由于我无法完全理解的原因,这对我来说并不合适。除了 process_meta_options 中的特定代码,有没有更 Mojolicious 的方法来做到这一点?例如,Mojo::UserAgent get() with userdefined callback使用 read事件,但我倾向于认为这可能会干扰事情。或者我可能只是想多了。

use v5.20;

use feature qw(signatures);
no warnings qw(experimental::signatures);

use Data::Dumper;
use Mojo::UserAgent;

my $ua = Mojo::UserAgent->new;

my $tx = $ua->build_tx( GET => 'http://blogs.perl.org' ); 

$tx->res->on(
    finish => \&process_meta_options
    );

$tx = $ua->start( $tx );
say "At end, charset is ", $tx->res->content->charset;

sub process_meta_options ( $res ) {
    $res
        ->dom
        ->find( 'head meta[charset]' )  # HTML 5
        ->map( sub {
            my $content_type = $res->headers->header( 'Content-type' );
            return unless my $meta_charset = $_->{charset};
            $content_type =~ s/;.*//;
            $res->headers->header( 'Content-type', "$content_type; charset=$_->{charset}" );
            } );
    }

最佳答案

我想答案正是我想出来的。我还没有找到任何我更喜欢的东西。

use v5.20;

use feature qw(signatures);
no warnings qw(experimental::signatures);

use Data::Dumper;
use Mojo::UserAgent;

my $ua = Mojo::UserAgent->new;

my $tx = $ua->build_tx( GET => 'http://blogs.perl.org' ); 

$tx->res->on(
    finish => \&process_meta_options
    );

$tx = $ua->start( $tx );
say "At end, charset is ", $tx->res->content->charset;

sub process_meta_options ( $res ) {
    $res
        ->dom
        ->find( 'head meta[charset]' )  # HTML 5
        ->map( sub {
            my $content_type = $res->headers->header( 'Content-type' );
            return unless my $meta_charset = $_->{charset};
            $content_type =~ s/;.*//;
            $res->headers->header( 'Content-type', "$content_type; charset=$_->{charset}" );
            } );
    }

关于perl - 我应该如何使用 Mojo::UserAgent 处理 HTML META 标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32472378/

相关文章:

perl - 如何使用 Mojo::DOM 设置节点的属性?

json - 使用 Mojo::UserAgent 并访问 JSON 作为响应?

arrays - 使用 Perl 比较一组字符串和一个文件

用于访问网页的 Perl 脚本

javascript - WWW::Scripter 问题与 window.history

Perl 测试 - 收到编译警告,但测试仍然顽固地表明一切正常

perl - 如何在 Mojolicious 中测试重定向?

perl - 如何取消来自 Mojo::UserAgent 的正在进行的请求?