【问题标题】:How should I process HTML META tags with Mojo::UserAgent?我应该如何使用 Mojo::UserAgent 处理 HTML META 标签?
【发布时间】:2017-07-01 21:55:28
【问题描述】:

我不得不使用一些配置错误的 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}" );
            } );
    }

【问题讨论】:

  • 我认为你想多了:-P 带有完成事件的后处理在这里听起来很合理。

标签: perl mojolicious mojo-useragent


【解决方案1】:

我认为答案正是我想出的。我还没有找到我更喜欢的东西。

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}" );
            } );
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-07
    • 2019-02-14
    • 2011-10-30
    • 2020-05-14
    • 2014-04-23
    • 2018-11-30
    • 1970-01-01
    相关资源
    最近更新 更多