忍者ブログ

ひつ(じのひよこが)プログラミングします。
お仕事や趣味で困ったこととか、何度も「あれ?どうだったかしら」と調べたりしたこととか、作ったものとか、こどものこととかを書きます
★前は週末定期更新でしたが今は不定期更新です

2024/04    03« 1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30  »05

Perl でウェブページの OGP の情報を取得する

もっとモジュール使えば楽、特に HTML のパースはそうなんだろうけど、さくらインターネットのレンタルサーバ ライトプランで動くことを前提に書いている。

#!/usr/bin/perl

use HTML::Parser ();
use LWP::UserAgent;
use JSON::PP;
use CGI;
use Encode;

my $cgi = CGI::new();
my $browser = LWP::UserAgent->new;
my $enc = "utf8";

print "Status: 200 OK\n";
print "Content-Type: application/json; charset=UTF-8\n\n";

my $url = $cgi->url_param('url');
my %ogps = (result => "OK");

sub when_open_tag_found {
  my ($self, $tagname, $attr) = @_;
  if($tagname eq 'meta' and $attr->{'property'} and $attr->{'content'} ){
    $ogps{$attr->{'property'}} = Encode::decode($enc, $attr->{'content'});
  }
  if($tagname eq 'meta' and $attr->{'name'} and $attr->{'content'} ){
    $ogps{$attr->{'name'}} = Encode::decode($enc, $attr->{'content'});
  }
}

if($url) {
  eval {
    my $response = $browser->get($url);
    $ogps{'url'} = $url;

    my $parser = HTML::Parser->new(
        api_version => 3,
        start_h     => [\&when_open_tag_found, "self, tagname, attr"]);
    $parser->parse($response->content);

    my $json = JSON::PP->new->utf8->space_after->encode(\%ogps);
    print $json;
  };
  if (my $error = $@) {
    $json = JSON::PP->new->utf8->space_after->encode({
      result => "NG",
      message => $error
    });
    print $json;
  }
} else {
  print '{"result": "NG", "message":"No URL is found in parameter"}'
}

exit;
PR

コメント

ただいまコメントを受けつけておりません。

ブログ内検索

P R