ルモーリン

Perlサンプル30 togetterからツイートを拾う

投稿:2022-06-08

#!/usr/bin/env perl -w

use utf8;
use v5.32;
use strict;
use warnings;

use Encode;
use Encode::Argv;
use Encode::Locale;
use File::Basename;
use Getopt::Long qw(:config auto_help);
use HTML::TreeBuilder;
use LWP::UserAgent;
use Pod::Usage;
use Text::CSV qw/ csv /;

binmode STDIN, ":encoding(console_in)";
binmode STDOUT, ":encoding(console_out)";
binmode STDERR, ":encoding(console_out)";

my $togetter;
GetOptions(
	"togetter=s" => \$togetter,
) or die "オプションが誤っている";
$togetter or pod2usage(-exitval => 0, -verbose => 2);
@ARGV and die "不要なオプションがある:'@ARGV'";

my $ua = LWP::UserAgent->new;
my $res = $ua->get($togetter);
$res->is_success or die "ページを拾えない";
my $content = $res->decoded_content;
my $tree = HTML::TreeBuilder->new;
$tree->parse($content);
$tree->eof;

use constant HEADER => qw / タイムスタンプ アカウント ツイートID /;
my @tsv;
for ($tree->look_down(class => "status")) {
	my $tweet = $_->look_down(class => "link");
	my ($user) = $tweet->attr("href") =~ m#https://twitter.com/(.+)/status/\d+$#;
	my @item = ($tweet->attr("data-timestamp"), $user, $_->attr("data-id"));

	my %row;
	$row{$_} = shift @item for HEADER;
	push @tsv, \%row;
}

my $tsv_file = basename(__FILE__, ".pl") . ".tsv";

csv(
	encoding => "utf8",
	headers => [HEADER],
	in => \@tsv,
	out => $tsv_file,
	sep_char => "\t",
);

=pod

=encoding utf8

=head1 NAME

togetterのツイート拾い

=head1 SYNOPSIS

perl perlsample_030.pl --togetter <togetterのURL>

=head1 DESCRIPTION

togetterのツイートをTSVファイルに保存します。
まとめたツイートの他にコメントのツイートも一緒くたです(笑)。

=cut

オプションなしでマニュアルを表示します。

> perl perlsample_030.pl 
NAME
    togetterのツイート拾い

SYNOPSIS
    perl perlsample_030.pl --togetter <togetterのURL>

DESCRIPTION
    togetterのツイートをTSVファイルに保存します。 まとめたツイートの他にコメントのツイートも一緒くたです(笑)。

--helpを付けると簡単な説明を表示します。

> perl perlsample_030.pl --help
Usage:
    perl perlsample_030.pl --togetter <togetterのURL>

--togetter <togetterのURL>を指定するとTSVファイルを保存します。

> perl perlsample_030.pl --togetter https://togetter.com/li/1896643

何も表示されませんけれど代わりにperlsample_030.tsvが作成されます。

"タイムスタンプ"	"アカウント"	"ツイートID"
1654077882	yukinohotel	1531939789699940352
1654080658	tunatu727	1531951434727428099
1654083633	yukinohotel	1531963910106009602
1654082885	Milky84624474	1531960774658510849
1654083747	perorist_pero	1531964388072357889
1654127122	2nZHXAV5FGO2cHC	1532146317178568704
1654166631	7roHzeKuu7069mR	1532312030618996736
1654164360	SUdagagawa	1532302505476235264
1654156152	tellmebio42	1532268076909346816
1654154291	hrmr35580844	1532260272823758848
1654087594	3qhyudKbHGZPmDL	1531980524264206337
1654262768	dabedabesan	1532715256518103040