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 = '1.00';
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 from_website => 1,
38 };
39 }
40  
41 return @websites;
42 }
43  
44 sub getWebsiteHtml {
45 my $self = shift;
46 my $url = shift;
47  
48 my $ua = new LWP::UserAgent;
49 $ua->agent( "$0/0.1 " . $ua->agent );
50  
51 my $req = new HTTP::Request 'GET' => $url;
52 $req->header( 'Accept' => 'text/html' );
53  
54 my $res = $ua->request($req);
55  
56 return $res->decoded_content;
57 }
58  
59 sub extractArticles {
60 my $self = shift;
61 my $resource = shift;
62 my $content = $self->getWebsiteHtml( $resource->{url} );
63 my $dom = Mojo::DOM->new($content);
64 my $found = $dom->find( $resource->{selector} );
65  
66 my @articles = ();
67  
68 foreach ( $found->each ) {
69 my $text = $_->find( $resource->{textSelector} )->[0]->text;
70 my $link = $_->find( $resource->{linkSelector} )->[0]->attr->{href};
71  
72 $text =~ s/^\s+|\s+$//g;
73  
74 push @articles,
75 {
76 text => encode( 'utf8', $text ),
77 link => $link
78 };
79 }
80  
81 return @articles;
82 }
83  
84 1;