我应该如何使用Mojo :: UserAgent处理HTML META标签? [英] How should I process HTML META tags with Mojo::UserAgent?
问题描述
我必须使用一些配置错误的Web服务器,因此我开始处理HTML元标记以将信息反馈到Web用户代理对象中.我在 Mojolicious 中尝试了多种方法,然后决定在响应中查找完成"事件.我的目标是使其余代码几乎看不到它,因此过程甚至都不知道这种情况在发生.
I have to play with some misconfigured web servers, so I started processing the HTML meta tags to feed information back into the web user-agent object. I tried a variety of ways of doing this in Mojolicious and settled on a looking for a "finish" event on the response. My goal was to make this mostly invisible to the rest of the code so the process wasn't even aware this was happening.
不过,由于我无法完全放下手指,这只是不适合我.除了process_meta_options
中的特定代码之外,还有其他Mojolicious方式可以做到这一点吗?例如,带有用户定义的回调的Mojo :: UserAgent get()使用read
事件,但我倾向于认为这可能会干扰事物.否则我可能会考虑过度.
Still, this just doesn't sit right with me for a reason I can't quite put my finger on. Aside from the particular code in process_meta_options
, is there a more Mojolicious way to do this? For example, Mojo::UserAgent get() with userdefined callback uses the read
event, but I tend to think that might interfere with things. Or I could just be over-thinking it.
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}" );
} );
}
推荐答案
我认为答案就是我想出的.我没有发现我更喜欢的东西.
I think the answer is just what I came up with. I haven't found anything that I liked better.
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}" );
} );
}
这篇关于我应该如何使用Mojo :: UserAgent处理HTML META标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!