Scrap/WebsiteScrapper.pm untested

filter: Statementstmt 0.0% 0 / 54 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 0.0% 0 / 11 Podpod 0.0% 0 / 4 totaltotal 0.0% 0 / 69 CC 1 SCAR 6.9
CC
1
Cov
0%
new
2.0
scrap
2.0
getWebsiteHtml
2.0
CRAP 2.0
1 package Fancazzista::Scrap::WebsiteScrapper;
2  
3 use strict;
4 use warnings;
5 use LWP::UserAgent;
6 use HTTP::Request;
7 use Mojo::DOM;
8 use JSON;
9 use Encode qw(encode);
10  
11 our $VERSION = '0.01';
12  
13 sub new {
14 my $class = shift;
15  
16 my $self = {};
17  
18 bless $self, $class;
19  
20 return $self;
21 }
22  
23 sub scrap {
24 my $self = shift;
25 my $config = shift;
26  
27 my @websites = ();
28  
29 foreach ( @{ $config->{websites} } ) {
30 my @resourceArticles = $self->extractArticles($_);
31  
32 push @websites,
33 {
34 name => $_->{name},
35 url => $_->{url},
36 articles => \@resourceArticles
37 };
38 }
39  
40 return @websites;
41 }
42  
43 sub getWebsiteHtml {
44 my $self = shift;
45 my $url = shift;
46  
47 my $ua = new LWP::UserAgent;
48 $ua->agent( "$0/0.1 " . $ua->agent );
49  
50 my $req = new HTTP::Request 'GET' => $url;
51 $req->header( 'Accept' => 'text/html' );
52  
53 my $res = $ua->request($req);
54  
55 return $res->decoded_content;
56 }
57  
58 sub extractArticles {
59 my $self = shift;
60 my $resource = shift;
61 my $content = $self->getWebsiteHtml( $resource->{url} );
62 my $dom = Mojo::DOM->new($content);
63 my $found = $dom->find( $resource->{selector} );
64  
65 my @articles = ();
66  
67 foreach ( $found->each ) {
68 my $text = $_->find( $resource->{textSelector} )->[0]->text;
69 my $link = $_->find( $resource->{linkSelector} )->[0]->attr->{href};
70  
71 $text =~ s/^\s+|\s+$//g;
72  
73 push @articles,
74 {
75 text => encode( 'utf8', $text ),
76 link => $link
77 };
78 }
79  
80 return @articles;
81 }
82  
83 1;