fuba (owner)

Revisions

gist: 40029 Download_button fork
public
Description:
exthtml.pl extracts contents specified by an xpath from web pages. Cookbook in Japanese: http://fuba.jottit.com/exthtml
Public Clone URL: git://gist.github.com/40029.git
Embed All Files: show embed
exthtml.pl #
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
#!/usr/bin/perl
use strict;
use warnings;
 
use Encode;
use Getopt::Long;
 
use URI;
use LWP::UserAgent;
use HTTP::Cookies::Guess;
 
use constant CHARSET => 'utf-8';
 
my $VERSION = '20090121_1';
 
my $url = pop @ARGV;
 
my (
    $xpath, $referer, $cookie, $agent, $nextlink,
    $depth, $as_xml, $verbose, $procedure, $weight,
);
my $result = GetOptions(
    "x|xpath=s" => \$xpath,
    "e|referer=s" => \$referer,
    "c|cookie-jar=s" => \$cookie,
    "a|agent=s" => \$agent,
    "n|nextlink=s" => \$nextlink,
    "d|depth=i" => \$depth,
    "s|as-source" => \$as_xml,
    "f" => \$verbose,
    "p|procedure=s" => \$procedure,
    "w=i" => \$weight,
);
 
$depth += 1;
 
unless ($url && $xpath) {
    die "version $VERSION\nusage: ./exthtml.pl [ -a [AGENT] -e [REFERER] -c [COOKIE_JAR]"
        ." -n [NEXTPAGE_XPATH] -d [NEXTPAGE_DEPTH] -w [NEXTPAGE_SLEEP(sec)]"
        ." -p [PROCEDURE: \$v(scalar value), \$n(HTML::Element object), \$u(URI object)]"
        ." -s -f ] -x [XPATH] [URL]|-";
}
 
my $ua = LWP::UserAgent->new;
$ua->cookie_jar(HTTP::Cookies::Guess->create(file => $cookie)) if ($cookie);
$ua->agent($agent) if ($agent);
 
my %options_base = (
    xpath => decode(CHARSET, $xpath),
    referer => $referer,
    ua => $ua,
    as_xml => $as_xml,
    nextlink => decode(CHARSET, $nextlink),
    depth => $depth,
    verbose => $verbose,
    procedure => $procedure,
    weight => $weight || 0,
);
 
my @url_list;
if ($url eq '-') {
    while (my $url_line = <>) {
        chomp $url_line;
        push @url_list, $url_line;
    }
}
else {
    if ($url =~ /\[\d+\-\d+\]/) {
        push @url_list, &expand_url($url);
    }
    else {
        push @url_list, $url;
    }
}
 
if (@url_list) {
    for my $url_line (@url_list) {
        my %options = %options_base;
        $options{url} = $url_line;
        extract(%options);
    }
}
 
exit;
 
sub expand_url {
    my $exp = shift;
    
    my @urls;
    my $format = '%d';
    if ($exp =~ s/\[(\d+)\-(\d+)\]/[NUM]/) {
        my ($start, $end) = ($1 <= $2) ? ($1, $2) : ($2, $1);
        if ($start =~ /^0\d/) {
            $format = '%0'.length($end).'d';
        }
        for my $num ($start..$end) {
            my $url = $exp;
            my $numstr = sprintf($format, $num);
            $url =~ s/\[NUM\]/$numstr/;
            push @urls, $url;
        }
        @urls = map {expand_url($_)} @urls;
    }
    else {
        return $exp;
    }
 
    return @urls;
}
 
sub proc {
    my ($proc, $n, $v, $u) = @_;
    return eval($proc);
}
 
sub extract {
    my %opt = @_;
    my $xpath = $opt{xpath};
    my $depth = $opt{depth};
    my $url = $opt{url};
    my $referer = $opt{referer};
    my $procedure = $opt{procedure};
    my $weight = $opt{weight} || 0;
 
    my %hist;
 
    while ($url && ($depth--)) {
        last if ($hist{$url});
        $hist{$url} = 1;
 
        print "$url\n" if ($opt{verbose});
        my $tree = HTML::TreeBuilder::XPath::Remote->new_from_uri(
            $url, $opt{ua}, $referer
        );
        
        for my $node ($tree->findnodes($opt{xpath})) {
            print "\t" if ($opt{verbose});
            my $value = ($opt{as_xml} && $node->isa('HTML::Element'))
                ? $node->as_XML('<>&"')
                : $node->getValue."\n";
            $value = proc($procedure, $node, $value, URI->new($url)) if ($procedure);
 
            print encode(CHARSET, $value);
        }
        
        $referer = $url;
        $url = '';
 
        if ($opt{nextlink}) {
            my @urls =
                grep /^http/,
                map {$_->getValue} $tree->findnodes($opt{nextlink});
            $url = $urls[0] if (@urls);
        }
        $tree->delete;
        sleep $weight;
    }
}
 
package HTML::TreeBuilder::XPath::Remote;
use strict;
use warnings;
 
use List::Util qw( first );
 
use Encode;
 
use HTML::TreeBuilder::XPath;
use HTML::ResolveLink;
 
use LWP::UserAgent;
use HTTP::Request;
use HTTP::Response::Encoding;
 
sub new_from_uri {
    my ($pkg, $uri, $ua, $referer) = @_;
    
    my $resolver = HTML::ResolveLink->new(
        base => $uri,
    );
    
    my $html = $resolver->resolve(
        $pkg->get($uri, $ua, $referer)
    );
 
    return HTML::TreeBuilder::XPath->new_from_content($html);
}
 
sub get {
    my ($self, $uri, $ua, $referer) = @_;
    
    my $html;
    
    $ua ||= LWP::UserAgent->new();
    my $req = HTTP::Request->new('GET', $uri);
    $req->header(referer => $referer) if ($referer);
    
    my $res = $ua->request($req);
    
    # this detection is based on Web::Scraper.
    if ($res->is_success) {
        my @encoding = (
            $res->encoding,
            ($res->header('Content-Type') =~ /charset=([\w\-]+)/g),
        );
        
        if (eval {require Encode::Detect;}) {
            push @encoding, "Detect";
        }
        push @encoding, "shift-jis";
 
        my $encoding = first {
            defined $_ && Encode::find_encoding($_)
        } @encoding;
 
        $html = Encode::decode($encoding, $res->content);
    }
    return $html;
}
 
1;