-
Notifications
You must be signed in to change notification settings - Fork 0
/
kamate_scrape
executable file
·268 lines (226 loc) · 8.2 KB
/
kamate_scrape
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
#!/usr/bin/perl -wT
#
# Matija Nalis <mnalis-perl@voyager.hr> AGPLv3+ started on 2018-03-21
#
# logira kretanje kamata na stednju u HR
#
use strict;
use autodie qw(:all);
use feature qw(say);
my $DB='dbi:SQLite:dbname=kamate.db'; # undef to skip database ops
my $DBUSER='';
my $DBPASS='';
my $DIR = './banks';
my $DEBUG = $ENV{DEBUG} || 0;
my $FORCE = $ENV{FORCE} || 0;
%ENV = ( PATH => '/usr/local/bin:/usr/bin:/bin' );
our $USER_AGENT_FAKE='Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.90 Safari/537.36 2345Explorer/9.3.2.17332';
our $USER_AGENT = 'like Wget/1.18 (linux-gnu) - WWW::Mechanize';
use POSIX qw(strftime);
use FindBin;
use WWW::Mechanize;
use DBI;
use File::Temp qw( tempfile unlink0 );
our $mech;
# debug helper
sub dbg($$) {
my ($level, $txt) = @_;
die "invalid call: dbg($level,$txt)" if $level !~ /^\d{1,3}$/;
if ($DEBUG >= $level) {
print " " x ($level-1); # ident
say $txt;
}
}
# extract domain name only from URL
sub extract_domain($) {
my ($url) = @_;
die "cannot extract domain from URL $url" if $url !~ m{^\s*https?://(www[0-9]?\.)?(?'DOMAIN'.*?)(/.*)?$}i;
my $domain = $+{DOMAIN};
dbg 4, "extracted domain $domain from url >$url<";
return $domain;
}
# scans file for any url, and return first one
sub scan_for_url ($) {
my ($file) = @_;
open my $fd, '<', $file;
my $html = do { local $/; <$fd>; }; # slurp text version of .pdf
die "cannot find URL in $file" if $html !~ m{["'](https?://.*?)['"]};
my $url = $1;
dbg 3, "scanned in $file for URL, found $url";
return $url;
}
# pronalazi najbolju kamatu u zadanom stringu po regexu
sub find_max_kamata_regex($$) {
my ($html, $regex) = @_;
our $best_kamata = 0;
# provjera kamate
sub check_kamata($) {
my ($pct) = @_;
dbg 5, "provjeravam kamatu $pct <=> $best_kamata";
$best_kamata = $pct if $pct > $best_kamata;
}
dbg 4, "using per-kamata regex: $regex";
dbg 8, "searching in extracted content: $html";
$html =~ s{$regex}{check_kamata("$1.$2")}gme;
dbg 3, "best_kamata=$best_kamata";
return $best_kamata;
}
# pronalazi max kamatu sa zadanim $PRE i $POST u standardnom regexpu
sub find_max_kamata_pp($$$) {
my ($html, $pre, $post) = @_;
my $regex = "$pre" . '([1-9]?\d)[.,](\d{2})' . "$post";
return find_max_kamata_regex($html, $regex);
}
# fetches URL and returns content as string
sub fetch_url($) {
my ($url) = @_;
$mech = WWW::Mechanize->new();
$mech->agent($USER_AGENT);
$mech->ssl_opts(verify_hostname => 0, SSL_verify_mode => 0x00); # kludge: allow fetching of broken HTTPS, FIXME! /mn/ 20220414 needed for pbz-stambena.hr, 20221026 for agrambanka.hr
dbg 2, "Getting $url";
dbg 3, "using UA=$USER_AGENT";
$mech->get($url);
die "can't fetch $url: " . $mech->response() if !$mech->success();
return $mech->content;
}
# povlaci zadani URL i vraca najbolju kamatu koju pronadje na stranici a matchira $PRE i $POST
sub best_kamata_html_mpp($$$$) {
my ($url, $match, $pre, $post) = @_;
my $html = fetch_url($url);
$html =~ s{<!--.*?-->}{}sg; # remove HTML comments
if ($match) {
dbg 4, "matching only code in $match";
if ($html =~ /$match/s) { $html = $1 } else { die "$html\ndoesn't match $match" }
}
return find_max_kamata_pp($html, $pre, $post);
}
# povlaci zadani URL i vraca najbolju kamatu koju pronadje na stranici a matchira $REGEX
sub best_kamata_html_regex($$$) {
my ($url, $match, $regex) = @_;
my $html = fetch_url($url);
$html =~ s{<!--.*?-->}{}sg; # remove HTML comments
if ($match) {
dbg 4, "matching only code in $match";
if ($html =~ /$match/si) { $html = $1 } else { die "$html\ndoesn't match $match" }
}
return find_max_kamata_regex($html, $regex);
}
# povlaci zadani URL i vraca najbolju kamatu koju pronadje na stranici sa default formatom: x,xx%
sub best_kamata_html_def($) {
my ($url) = @_;
return best_kamata_html_mpp ($url, '<body(.*)</body>', '\b', '\s*\%');
}
# povlaci $pdf iz $mech->content (dobiven npr. za $mech->follow_link()) i vraca najbolju kamatu koju pronadje na stranici a matchira $PRE i $POST
sub best_kamata_pdf_mpp($$$) {
my ($match, $pre, $post) = @_;
die $mech->response() if !$mech->success();
#print "html=$html";
my ($temp_fd, $tempfile) = tempfile(); # save .pdf to tempfile
$mech->save_content($tempfile);
open my $txt_fd, '-|', 'pdftotext', $tempfile, '-';
my $text = do { local $/; <$txt_fd>; }; # slurp text version of .pdf
unlink0($temp_fd, $tempfile);
if ($match) {
dbg 4, "matching only code in $match";
if (my @matches = $text =~ /$match/si) { $text = join(' ', @matches) } else { die "$text\ndoesn't match $match" } # use all capture groups, not just first one
}
return find_max_kamata_pp($text, $pre, $post);
}
# povlaci $pdf iz $mech->content (dobiven npr. za $mech->follow_link()) i vraca najbolju kamatu koju pronadje na stranici sa default formatom: x,xx%
sub best_kamata_pdf_def() {
return best_kamata_pdf_mpp (undef, '\b', '\s*\%');
}
###############################################
# here goes the main
###############################################
my $cwd = $FindBin::Bin;
if ($cwd =~ m{^([a-z0-9_.\-\/]+)$}) { $cwd = $1 } else { die "invalid chars in CWD $cwd" }
chdir ($cwd) or die "can't chdir to cwd $cwd: $!";
umask 0077;
my $dbh;
if ($DB) {
$dbh = DBI->connect("$DB","$DBUSER","$DBPASS");
$dbh->do ("CREATE TABLE IF NOT EXISTS kamate (
bank varchar(60) NOT NULL,
pct10 int NOT NULL,
datum int DEFAULT CURRENT_DATE NOT NULL,
UNIQUE (datum,bank),
UNIQUE (bank,datum) )
") or die $dbh->errstr;
$dbh->begin_work or die $dbh->errstr;
}
opendir(my $dh, $DIR) || die "Can't opendir $DIR: $!";
my @banks = sort grep { s/\.pm$// && -f "$DIR/$_.pm" } readdir($dh);
closedir $dh;
my $manual = 0;
if (scalar @ARGV > 0) {
@banks = @ARGV;
$manual = 1;
}
# DAB.hr parsing list of banks
my $html = fetch_url('http://www.haod.hr/clanice');
$html =~ s{^.*Popis .*?lanica sustava osiguranja.*?(<ol>.*?</ol>).*$}{$1}si;
dbg (9, "DAB HTML=$html");
$mech->update_html($html);
my @dab_banks = $mech->find_all_links();
our %DAB_BANKS = ();
# list of all banks at DAB.HR
foreach my $bank (@dab_banks) {
my $url = $bank->url();
my $domain = extract_domain($url);
dbg 3, "DAB bank URL=$url, domain=$domain";
$DAB_BANKS{$domain} = -1;
}
my $sth_check = $dbh->prepare ('SELECT pct10 from kamate where bank=? and datum=?') or die $dbh->errstr; # only check banks which do not have info for today
my $now = strftime "%Y-%m-%d", localtime;
# parse banks one by one
foreach my $bank (@banks) {
if ($bank =~ /^([a-z0-9_-]+)$/) { $bank = $1 } else { die "invalid bank name: $bank" }
my $bankcmd = "$DIR/$1.pm";
if (! -r "$bankcmd" ) { die "can't read bank $bank in cmd $bankcmd" }
my $bank_domain = extract_domain(scan_for_url($bankcmd));
dbg 3, "increasing bank count from DAB_BANKS{$bank_domain} for domain $bank_domain";
$DAB_BANKS{$bank_domain}++; # increase bank from -1 to 0 (if everything is ok; or from undef to 1 if it is not)
my $rv = $sth_check->execute($bank, $now) or die $sth_check->errstr;
dbg 4,"rv=$rv for bank=$bank now=$now";
dbg 1, "*** Processing bank: $bank";
$mech=undef;
if (! $FORCE) {
my @values = $sth_check->fetchrow_array;
if (@values && $values[0] > 0) {
my $pct = sprintf '%0.2f', $values[0]/100;
if (! $manual) {
say "$pct\t$bank (cached)";
dbg 1, "*** Already have pct=$pct for $bank at $now, skipping...";
next;
}
}
}
my $pct = 0;
my $ret = eval { $pct = require "$bankcmd"; };
dbg 2, "finished $bank: pct=$pct ret=" . ($ret ? $ret : "undef");
if (! $ret) {
warn "neuspjesno dohvacanje banke $bank ($pct): $@";
next;
}
say "$pct\t$bank";
if ($pct <= 0) { die "invalid kamata $pct for $bank"; }
if ($DB) {
my $sth = $dbh->prepare ('REPLACE INTO kamate (bank,pct10) VALUES (?,?)') or die $dbh->errstr;
$sth->execute ($bank, $pct*100) or die $sth->errstr;
}
}
$dbh->commit or die $dbh->errstr;
# bank $src is gone. specify $dst if separate page on destination bank, or leave undef
sub bank_merge($$) {
my ($src, $dst) = @_;
$DAB_BANKS{$src}++ if $src;
$DAB_BANKS{$dst}-- if $dst;
}
# exceptions to dab.hr (now haod.hr) bugs 20220420
bank_merge (undef, 'bks.hr'); # BKS vise nije unatar DAB osiguranja, ali je unutar ekvivalentnog EU osiguranja
foreach my $bank (keys %DAB_BANKS) {
if ($DAB_BANKS{$bank} != 0) {
warn "sumnjiv status banke $bank ($DAB_BANKS{$bank})";
}
}