-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathdefault.py
executable file
·2229 lines (1890 loc) · 78.5 KB
/
default.py
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Greynir: Natural language processing for Icelandic
Default scraping helpers module
Copyright (C) 2023 Miðeind ehf.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/.
This module implements a set of default scraping helpers for
a number of Icelandic websites. The particular scraping module and
class to be used for each root website is specified in the roots
table of the scraper database.
"""
from __future__ import annotations
from typing import Iterable, Match, Optional, Sequence, Union, List, cast
import re
import logging
import urllib.parse as urlparse
import requests
import json
from datetime import datetime, timezone
from bs4 import BeautifulSoup
from bs4.element import Tag, NavigableString
from db.models import Root
MODULE_NAME = __name__
# The HTML parser to use with BeautifulSoup
# _HTML_PARSER = "html5lib"
_HTML_PARSER = "html.parser"
# Icelandic month names. Used for parsing
# date strings in some of the scrapers
MONTHS: Sequence[str] = [
"janúar",
"febrúar",
"mars",
"apríl",
"maí",
"júní",
"júlí",
"ágúst",
"september",
"október",
"nóvember",
"desember",
]
MONTHS_ABBR: Sequence[str] = [
"jan",
"feb",
"mar",
"apr",
"maí",
"jún",
"júl",
"ágú",
"sep",
"okt",
"nóv",
"des",
]
def _now() -> datetime:
"""Return the current time in UTC"""
return datetime.now(timezone.utc)
class Metadata:
"""The metadata returned by the helper.get_metadata() function"""
def __init__(
self,
heading: Optional[str],
author: str,
timestamp: datetime,
authority: float,
icon: str,
) -> None:
self.heading = heading
self.author = author
self.timestamp = timestamp
self.authority = authority
self.icon = icon
def __repr__(self) -> str:
return "{0}(heading='{1}', author='{2}', ts='{3}')".format(
type(self).__name__, self.heading, self.author, self.timestamp
)
class ScrapeHelper:
"""Generic scraping helper base class"""
def __init__(self, root: Root) -> None:
self._domain = root.domain
self._authority = root.authority
self._author = root.author
self._description = root.description
self._root_id = root.id
self._feeds: List[str] = []
def make_soup(self, doc: str) -> Optional[BeautifulSoup]:
"""Make a soup object from a document"""
soup = BeautifulSoup(doc, _HTML_PARSER)
return None if soup.html is None else soup
def skip_url(self, url: str) -> bool:
"""Return True if this URL should not be scraped"""
return False # Scrape all URLs by default
def skip_rss_entry(self, entry: str) -> bool:
"""Return True if URL in RSS feed entry should be skipped"""
return False
@staticmethod
def unescape(s: str) -> str:
"""Unescape headings that may contain Unicode characters"""
def replacer(matchobj: Match[str]) -> str:
m = matchobj.group(1)
assert m
return chr(int(m, 16)) # Hex
# Example: \u0084 -> chr(132)
return re.sub(r"\\u([0-9a-fA-F]{4})", replacer, s) if s else ""
def get_metadata(self, soup: BeautifulSoup) -> Metadata:
"""Analyze the article HTML soup and return metadata"""
return Metadata(
heading=None,
author=self.author,
timestamp=_now(),
authority=self.authority,
icon=self.icon,
)
@staticmethod
def _get_body(soup: BeautifulSoup) -> Optional[Tag]:
"""Can be overridden in subclasses in special situations"""
return soup.html.body if soup.html else None
def get_content(self, soup: BeautifulSoup) -> Optional[Tag]:
"""Find the actual article content within an HTML soup
and return its parent node"""
if not soup or not soup.html or not soup.html.body:
# No body in HTML: something is wrong, return None
logging.warning("get_content returning None")
return None
f = getattr(self, "get_content")
if callable(f):
content = f(self._get_body(soup))
if content:
# Always delete embedded social media widgets
content = ScrapeHelper.del_social_embeds(content)
else:
content = None
# By default, return the entire body
return content or self._get_body(soup)
@property
def root_id(self) -> int:
"""Return the root id corresponding to this domain"""
return self._root_id
@property
def domain(self) -> str:
return self._domain
@property
def icon(self) -> str:
"""Return the name of an icon file for this root"""
return self._domain + ".png"
@property
def authority(self) -> float:
return 0 if self._authority is None else self._authority
@property
def author(self) -> str:
return self._author or ""
@property
def feeds(self) -> List[str]:
return self._feeds
@property
def scr_module(self) -> str:
"""Return the name of the module for this scraping helper class"""
return MODULE_NAME
@property
def scr_class(self) -> str:
"""Return the name of this scraping helper class"""
return self.__class__.__name__
@property
def scr_version(self) -> str:
"""Return the version of this scraping helper class"""
# If no VERSION attribute in the class, return a default '1.0'
return getattr(self.__class__, "VERSION", "1.0")
@staticmethod
def general_filter(
tag: Tag, name: str, attr: str, attr_val: Union[str, Iterable[str]]
) -> bool:
"""General filter function to use with BeautifulSoup.find().
Looks for tag['attr'] == attr_val or attr_val in tag['attr'].
attr_val can also be iterable, in which case all the given
attribute values must be present on the tag for the match to
be made."""
if tag.name != name or not tag.has_attr(attr):
return False
a = tag[attr]
assert a is not None
# Handle both potentially multi-valued attrs
# (for instance multiple classes on a div),
# and multi-valued attr_vals (for instance more
# than one class that should be present)
if isinstance(a, str):
a = set(a.split())
if isinstance(attr_val, str):
return attr_val in a
return all(v in a for v in attr_val)
@staticmethod
def meta_property_filter(
tag: Tag, prop_val: Union[str, Iterable[str]], prop_attr: str = "property"
) -> bool:
"""Filter function for meta properties in HTML documents"""
# By default, catch <meta property='prop_val' content='X'>
return ScrapeHelper.general_filter(tag, "meta", prop_attr, prop_val)
@staticmethod
def div_class_filter(tag: Tag, cls: Union[str, Iterable[str]]) -> bool:
"""Filter function for divs in HTML documents, selected by class"""
return ScrapeHelper.general_filter(tag, "div", "class", cls)
@staticmethod
def div_id_filter(tag: Tag, div_id: Union[str, Iterable[str]]) -> bool:
"""Filter function for divs in HTML documents, selected by id"""
return ScrapeHelper.general_filter(tag, "div", "id", div_id)
@staticmethod
def meta_property(
soup: BeautifulSoup, property_name: str, prop_attr: str = "property"
) -> Optional[str]:
try:
f = lambda tag: ScrapeHelper.meta_property_filter(
tag, property_name, prop_attr
)
mp = soup.html.head.find(f)
if not mp:
logging.warning(
f"meta property {property_name} not found in soup.html.head"
)
return str(mp["content"]) if mp else None
except Exception as e:
logging.warning(f"Exception in meta_property('{property_name}'): {e}")
return None
@staticmethod
def tag_prop_val(
soup: Tag, tag: str, prop: str, val: Union[str, Iterable[str]]
) -> Optional[Tag]:
"""Find a tag of a given type with an attribute having the specified value"""
if not soup:
return None
return soup.find(lambda t: ScrapeHelper.general_filter(t, tag, prop, val))
@staticmethod
def tag_class(
soup: BeautifulSoup, tag: str, cls: Union[str, Iterable[str]]
) -> Union[Tag, NavigableString, None]:
"""Find a tag of a given type with a particular class"""
return ScrapeHelper.tag_prop_val(soup, tag, "class", cls)
@staticmethod
def div_class(
soup: Union[Tag, NavigableString, None], *argv: Union[str, Sequence[str]]
) -> Optional[Tag]:
"""Find a div with a particular class/set of classes within the
HTML soup, recursively within its parent if more than one
div spec is given"""
if not soup:
return None
s = soup
for cls in argv:
def f(tag: Tag) -> bool:
return ScrapeHelper.div_class_filter(tag, cls)
s = soup.find(f)
return s
@staticmethod
def nested_tag(soup: Optional[Tag], *argv: str) -> Optional[Tag]:
"""Find a tag within a nested hierarchy of tags"""
for next_tag in argv:
if not soup:
return None
soup = soup.find(lambda tag: tag.name == next_tag)
return soup
@staticmethod
def div_id(soup: Tag, div_id: str) -> Optional[Tag]:
"""Find a div with a particular id"""
if not soup or not div_id:
return None
f = lambda tag: ScrapeHelper.div_id_filter(tag, div_id)
return soup.find(f)
@staticmethod
def del_tag_prop_val(
soup: Optional[Tag],
tag: str,
prop: str,
val: Union[str, Iterable[str]],
) -> None:
"""Delete all occurrences of the tag that have
a property with the given value"""
if soup is None:
return
while True:
s = ScrapeHelper.tag_prop_val(soup, tag, prop, val)
if s is None:
break
s.extract()
@staticmethod
def del_div_class(soup: Optional[Tag], *argv: Union[str, Sequence[str]]) -> None:
"""Delete all occurrences of the specified div.class"""
if soup is None:
return
while True:
s = ScrapeHelper.div_class(soup, *argv)
if s is None:
break
s.extract()
@staticmethod
def del_tag(soup: Optional[Tag], tag_name: str) -> None:
"""Delete all occurrences of the specified tag"""
if soup is None:
return
while True:
s = soup.find(lambda tag: tag.name == tag_name)
if s is None:
break
s.extract()
@staticmethod
def del_social_embeds(soup: Tag) -> Tag:
# Delete all iframes and embedded FB/Twitter/Instagram posts
ScrapeHelper.del_tag(soup, "iframe")
ScrapeHelper.del_tag(soup, "twitterwidget")
ScrapeHelper.del_div_class(soup, "fb-post")
ScrapeHelper.del_tag_prop_val(soup, "blockquote", "class", "instagram-media")
ScrapeHelper.del_tag_prop_val(soup, "blockquote", "class", "twitter-tweet")
return soup
class KjarninnScraper(ScrapeHelper):
"""Scraping helper for Kjarninn.is"""
def __init__(self, root: Root) -> None:
super().__init__(root)
self._feeds = ["https://kjarninn.is/feed/"]
def skip_url(self, url: str) -> bool:
"""Return True if this URL should not be scraped"""
s = urlparse.urlsplit(url)
if s.path and s.path.startswith("/tag/"):
return True
if s.path and s.path.startswith("/hladvarp/"):
return True
return False # Scrape all other URLs by default
def get_metadata(self, soup: BeautifulSoup) -> Metadata:
"""Analyze the article soup and return metadata"""
metadata = super().get_metadata(soup)
# Extract the heading from the OpenGraph (Facebook) og:title meta property
heading = ScrapeHelper.meta_property(soup, "og:title") or ""
if "|" in heading:
heading = heading[0 : heading.index("|")].rstrip()
heading = self.unescape(heading)
# Extract the publication time from the article:published_time meta property
ts = ScrapeHelper.meta_property(soup, "article:published_time")
if ts:
timestamp = datetime(
year=int(ts[0:4]),
month=int(ts[5:7]),
day=int(ts[8:10]),
hour=int(ts[11:13]),
minute=int(ts[14:16]),
second=int(ts[17:19]),
tzinfo=timezone.utc,
)
else:
timestamp = _now()
# Exctract the author name
# Start with <span itemprop="author">
f = lambda xtag: ScrapeHelper.general_filter(xtag, "span", "itemprop", "author")
tag = soup.html.body.find(f) if soup.html.body else None
if not tag:
# Then, try <span class="author">
f = lambda xtag: ScrapeHelper.general_filter(
xtag, "span", "class", "author"
)
tag = soup.html.body.find(f) if soup.html.body else None
if not tag:
logging.warning("span.class.author tag not found in soup.html.body")
author = str(tag.string) if tag and tag.string else "Ritstjórn Kjarnans"
metadata.heading = heading
metadata.author = author
metadata.timestamp = timestamp
return metadata
# noinspection PyMethodMayBeStatic
def get_content(self, soup: BeautifulSoup) -> Optional[Tag]:
"""Find the article content (main text) in the soup"""
article = cast(Optional[Tag], soup.find("article"))
if not article:
article = ScrapeHelper.div_class(soup, "article-body")
# soup_body has already been sanitized in the ScrapeHelper base class
if article is None:
logging.warning("Kjarninn scraper: soup_body article is None")
return None
# Delete div.container.title-container tags from the content
title_cont = ScrapeHelper.div_class(article, ("container", "title-container"))
if title_cont is not None:
title_cont.extract()
# Delete div.container.quote-container tags from the content
ScrapeHelper.del_div_class(article, ("container", "quote-container"))
# Delete div.container-fluid tags from the content
ScrapeHelper.del_div_class(article, "container-fluid")
# Get the content itself
content = ScrapeHelper.div_class(article, "article-body")
if content is None:
# No div.article-body present
content = article
# Delete div.category-snippet tags from the content
ScrapeHelper.del_div_class(content, "category_snippet")
# Delete image containers from content
ScrapeHelper.del_div_class(content, "image-container")
# Delete "Lestu meira" lists at bottom of article
ScrapeHelper.del_div_class(content, "tag_list_block")
# Delete div.ad-container tags from the content
ScrapeHelper.del_div_class(content, "ad-container")
# Delete sub-headlines
ScrapeHelper.del_tag(article, "h2")
ScrapeHelper.del_tag(content, "h3")
ScrapeHelper.del_tag(content, "h4")
return content
class RuvScraper(ScrapeHelper):
"""Scraping helper for RUV.is"""
def __init__(self, root: Root) -> None:
super().__init__(root)
self._feeds = ["https://www.ruv.is/rss/frettir"]
def skip_url(self, url: str) -> bool:
"""Return True if this URL should not be scraped"""
s = urlparse.urlsplit(url)
p = s.path
# Only scrape urls with the right path prefix
if p and p.startswith("/frettir/"):
return False # Don't skip
return True
def get_metadata(self, soup: BeautifulSoup) -> Metadata:
"""Analyze the article soup and return metadata"""
metadata = super().get_metadata(soup)
# Extract the heading from the OpenGraph (Facebook) og:title meta property
heading = ScrapeHelper.meta_property(soup, "og:title") or ""
heading = self.unescape(heading)
if " - " in heading:
# Remove the " - RÚV" suffix
heading = heading[0 : heading.index(" - ")].rstrip()
# Extract the publication time from the article:published_time meta property
timestamp = _now()
ts = ScrapeHelper.meta_property(soup, "article:published_time")
if ts:
try:
timestamp = datetime(
year=int(ts[0:4]),
month=int(ts[5:7]),
day=int(ts[8:10]),
hour=int(ts[11:13]),
minute=int(ts[14:16]),
second=int(ts[17:19]),
tzinfo=timezone.utc,
)
except Exception as e:
logging.warning(f"RuvScraper: Could not parse timestamp {ts}: {e}")
# Exctract the author name from meta property
author = ScrapeHelper.meta_property(soup, "article:author") or "Ritstjórn RÚV"
# Exctract the author name
metadata.heading = heading
metadata.author = author
metadata.timestamp = timestamp
return metadata
def get_content(self, soup: BeautifulSoup) -> Optional[Tag]:
"""Find the article content (main text) in the soup"""
content = BeautifulSoup("", _HTML_PARSER)
# Note: RÚV now uses client-side rendering. All the article
# content is now stored in a huge JSON object in a script tag.
script = soup.find("script", {"id": "__NEXT_DATA__"})
if not script:
return content
try:
data = json.loads(script.text)
bodies: List = data["props"]["pageProps"]["data"]["article"]["body"]
for b in bodies:
if not b or b["block_type"] != "text_block":
continue
content.append(BeautifulSoup(b["text_block"]["html"], _HTML_PARSER))
except Exception as e:
logging.warning(f"RuvScraper: Could not parse JSON: {e}")
return content
return content
class MblScraper(ScrapeHelper):
"""Scraping helper for Mbl.is"""
_SKIP_PREFIXES = [
"/fasteignir/",
"/english/",
"/frettir/bladamenn/",
"/frettir/sjonvarp/",
"/frettir/knippi/",
"/frettir/colorbox/",
"/frettir/lina_snippet/",
"/myndasafn/",
"/atvinna/",
"/vidburdir/",
"/sport/",
"/mogginn/",
]
def __init__(self, root: Root) -> None:
super().__init__(root)
self._feeds = [
"https://www.mbl.is/feeds/fp/",
"https://www.mbl.is/feeds/innlent/",
"https://www.mbl.is/feeds/erlent/",
"https://www.mbl.is/feeds/togt/",
"https://www.mbl.is/feeds/helst/",
"https://www.mbl.is/feeds/nyjast/",
"https://www.mbl.is/feeds/vidskipti/",
"https://www.mbl.is/feeds/200milur/",
"https://www.mbl.is/feeds/sport/",
"https://www.mbl.is/feeds/folk/",
"https://www.mbl.is/feeds/matur/",
"https://www.mbl.is/feeds/smartland/",
"https://www.mbl.is/feeds/bill/",
]
def skip_url(self, url: str) -> bool:
"""Return True if this URL should not be scraped"""
s = urlparse.urlsplit(url)
path = s.path
if path:
if any(path.startswith(p) for p in self._SKIP_PREFIXES):
return True
if "/breytingar_i_islenska_fotboltanum/" in path:
# Avoid lots of details about soccer players
return True
if "/felagaskipti_i_enska_fotboltanum/" in path:
return True
return False # Scrape all URLs by default
def get_metadata(self, soup: BeautifulSoup) -> Metadata:
"""Analyze the article soup and return metadata"""
metadata = super().get_metadata(soup)
url = ScrapeHelper.meta_property(soup, "og:url") or ""
# Extract the heading from the meta title or
# OpenGraph (Facebook) og:title property
heading = ScrapeHelper.meta_property(soup, "title", prop_attr="name") or ""
if not heading:
heading = ScrapeHelper.meta_property(soup, "og:title") or ""
if not heading:
# Check for a h2 inside a div.pistill-entry
p_e = ScrapeHelper.div_class(soup.html.body, "pistill-entry")
if p_e and p_e.h2:
heading = p_e.h2.string
if not heading:
h1 = soup.find("h1", {"class": "newsitem-fptitle"})
if h1:
heading = h1.get_text()
if heading:
if heading.endswith(" - mbl.is"):
heading = heading[0:-9]
if heading.endswith(" - K100"):
heading = heading[0:-7]
heading = heading.strip()
heading = self.unescape(heading)
# Extract the publication time from the article:published_time meta property
# A dateline from mbl.is looks like this: Viðskipti | mbl | 24.8.2015 | 10:48
dateline_elem = ScrapeHelper.div_class(soup.html.body, "dateline")
dateline = (
"".join(dateline_elem.stripped_strings).split("|") if dateline_elem else ""
)
timestamp = None
if dateline:
ix = 0
date = None
time = None
while ix < len(dateline):
if "." in dateline[ix]:
# Might be date
try:
date = [int(x) for x in dateline[ix].split(".")]
except:
date = None
elif ":" in dateline[ix]:
# Might be time
try:
time = [int(x) for x in dateline[ix].split(":")]
except:
time = None
if time and date:
# Seems we're done
break
ix += 1
if time and date:
try:
timestamp = datetime(
year=date[2],
month=date[1],
day=date[0],
hour=time[0],
minute=time[1],
tzinfo=timezone.utc,
)
except Exception as e:
logging.warning(
f"Exception when obtaining date of mbl.is article '{url}': {e}"
)
timestamp = None
if timestamp is None:
logging.warning(f"Failed to obtain date of mbl.is article '{url}'")
timestamp = _now()
# Extract the author name
rp = ScrapeHelper.div_class(soup.html.body, "frett-main", "reporter-profile")
f = lambda tag: ScrapeHelper.general_filter(tag, "a", "class", "name")
rname = rp.find(f) if rp else None
authname: Optional[str] = None
if rname:
authname = rname.string
else:
# Probably a blog post
rp = ScrapeHelper.div_class(soup.html.body, "pistlar-author-profile-box")
if rp and rp.h4:
authname = rp.h4.string
metadata.heading = heading
metadata.author = authname or "Ritstjórn mbl.is"
metadata.timestamp = timestamp
return metadata
def get_content(self, soup: BeautifulSoup) -> Optional[Tag]:
"""Find the article content (main text) in the soup"""
# 'New style' as of May 23, 2016
content = ScrapeHelper.div_class(soup, "main-layout")
if content is None:
# Revert to 'old style'
content = ScrapeHelper.div_class(soup, "frett-main")
if content is None:
# Could be a blog post
content = ScrapeHelper.div_class(soup, "pistill-entry-body")
if content is None:
# Subsection front page?
content = ScrapeHelper.tag_prop_val(soup, "main", "role", "main")
if content is None:
# Could be a picture collection - look for div#non-galleria
content = ScrapeHelper.div_id(soup, "non-galleria")
if content is None:
# Could be special layout for /ferdalog
content = ScrapeHelper.div_class(soup, "newsitem")
if content is None:
logging.warning(
"get_content: "
"soup_body.div.main-layout/frett-main/pistill-entry-body is None"
)
if content:
# Delete h1 tags from the content
s = content.h1
if s is not None:
s.decompose()
# Delete p/strong/a paragraphs from the content (intermediate links)
for p in content.find_all("p"):
try:
if p.strong and p.strong.a:
p.decompose()
except AttributeError:
pass
for ul in content.find_all("ul", {"class": "list-group"}):
ul.decompose()
deldivs = (
"info",
"reporter-profile",
"reporter-line",
"mainimg-big",
"extraimg-big-w-txt",
"extraimg-big",
"newsimg-left",
"newsimg-right",
"newsitem-image",
"newsitem-image-center",
"newsitem-fptitle",
"newsitem-intro",
"sidebar-row",
"reporter-line",
"newsitem-bottom-toolbar",
"sidebar-mobile",
"mbl-news-link",
"embedded-media",
"r-sidebar",
"big-teaser",
"imagebox",
"imagebox-description",
"augl",
"box-teaser",
"reporter-line",
)
for divclass in deldivs:
ScrapeHelper.del_div_class(content, divclass)
return content
class VisirScraper(ScrapeHelper):
"""Scraping helper for Visir.is"""
_SKIP_PREFIXES = [
"/english/",
"/section/", # All /section/X URLs seem to be (extreeeemely long) summaries
"/property/", # Fasteignaauglýsingar
"/lifid/",
"/paper/fbl/",
"/soyouthinkyoucansnap",
"/k/",
]
def __init__(self, root: Root) -> None:
super().__init__(root)
self._feeds = ["http://www.visir.is/rss/allt"]
def skip_url(self, url: str) -> bool:
"""Return True if this URL should not be scraped"""
s = urlparse.urlsplit(url)
if s.netloc.startswith("fasteignir.") or s.netloc.startswith("albumm."):
# Skip fasteignir.visir.is and albumm.visir.is
return True
if not s.path or any(s.path.startswith(p) for p in self._SKIP_PREFIXES):
return True
return False # Scrape all URLs by default
def skip_rss_entry(self, entry) -> bool:
# Skip live sport event pages
title = entry.title
if title.startswith("Í beinni: ") or title.startswith("Leik lokið: "):
return True
return False
def get_metadata(self, soup: BeautifulSoup) -> Metadata:
"""Analyze the article soup and return metadata"""
metadata = super().get_metadata(soup)
url = ScrapeHelper.meta_property(soup, "og:url") or ""
# Extract the heading from the OpenGraph (Facebook) og:title meta property
heading = ScrapeHelper.meta_property(soup, "og:title") or ""
heading = self.unescape(heading)
if heading.startswith("Vísir - "):
heading = heading[8:]
if heading.endswith(" - Glamour"):
heading = heading[:-10]
if heading.endswith(" - Vísir"):
heading = heading[:-8]
heading = heading.rstrip("|")
# Timestamp
timestamp = None
time_el = soup.find("time", {"class": "article-single__time"})
if time_el:
datestr = time_el.get_text().rstrip()
# Example: "21.1.2019 09:04"
if re.search(r"^\d{1,2}\.\d{1,2}\.\d\d\d\d\s\d{1,2}:\d{1,2}", datestr):
try:
timestamp = datetime.strptime(datestr, "%d.%m.%Y %H:%M").replace(
tzinfo=timezone.utc
)
except Exception:
pass
# Example: "17. janúar 2019 14:30"
else:
try:
(mday, m, y, hm) = datestr.split()
(hour, mins) = hm.split(":")
mday = mday.replace(".", "")
month = MONTHS.index(m) + 1
timestamp = datetime(
year=int(y),
month=int(month),
day=int(mday),
hour=int(hour),
minute=int(mins),
tzinfo=timezone.utc,
)
except Exception:
pass
if timestamp is None:
logging.warning(f"Could not parse date in visir.is article {url}")
timestamp = _now()
# Author
author = ScrapeHelper.tag_prop_val(soup, "a", "itemprop", "author")
if author and isinstance(author, Tag):
author = author.string
else:
# Check for an author name at the start of the article
article = ScrapeHelper.div_class(soup, "articlewrapper")
if article:
author = ScrapeHelper.div_class(article, "meta")
if author:
author = author.string
else:
# Updated format of Visir.is
article = ScrapeHelper.div_class(soup, "article-single__meta")
if article:
try:
author = article.span.a.string
except:
author = ""
if not author:
try:
author = article.span.string
except:
pass
if not author:
author = "Ritstjórn visir.is"
elif isinstance(author, str):
author = author.strip()
if author.endswith(" skrifar"):
# 'Jón Jónsson skrifar'
author = author[0:-8]
metadata.heading = heading.strip()
metadata.author = author
metadata.timestamp = timestamp
return metadata
@staticmethod
def _get_body(soup):
"""Hack to fix bug in visir.is HTML: must search entire
document, not just the html body"""
return soup
def get_content(self, soup: BeautifulSoup) -> Optional[Tag]:
"""Find the article content (main text) in the soup"""
# We shouldn't even try to extract text from the live sport event pages
liveheader = ScrapeHelper.div_id(soup, "livefeed-sporthead")
if liveheader:
return BeautifulSoup("", _HTML_PARSER) # Return empty soup.
result_soup = ScrapeHelper.div_class(soup, "article", "articletext")
if not result_soup:
# Check for new Visir layout
result_soup = ScrapeHelper.div_class(soup, "article-single__content")
if not result_soup:
# Check for normal Visir layout
result_soup = ScrapeHelper.div_class(soup, "articlewrapper")
if result_soup:
# Delete div.media from the content
ScrapeHelper.del_div_class(result_soup, "media")
# Delete div.meta from the content
ScrapeHelper.del_div_class(result_soup, "meta")
# Delete video players
ScrapeHelper.del_div_class(result_soup, "jwplayer")
ScrapeHelper.del_div_class(result_soup, "embedd-media-player")
# Delete figure tags from the content
if result_soup.figure:
result_soup.figure.decompose()
for fc in result_soup.find_all("figcaption"):
fc.decompose()
return result_soup
class EyjanScraper(ScrapeHelper):
"""Scraping helper for Eyjan.pressan.is"""
def __init__(self, root: Root) -> None:
super().__init__(root)
def get_metadata(self, soup: BeautifulSoup) -> Metadata:
"""Analyze the article soup and return metadata"""
metadata = super().get_metadata(soup)
# Extract the heading from the OpenGraph (Facebook) og:title meta property
heading = ScrapeHelper.meta_property(soup, "og:title") or ""
heading = self.unescape(heading)
# Extract the publication time from the <span class='date'></span> contents
dateline_elem = ScrapeHelper.div_class(soup, "article-full")
dateline_elem = ScrapeHelper.tag_class(dateline_elem, "span", "date")
dateline = (
"".join(dateline_elem.stripped_strings).split() if dateline_elem else ""
)
timestamp = None
if dateline:
# Example: Þriðjudagur 15.12.2015 - 14:14
try:
date = [int(x) for x in dateline[1].split(".")]
time = [int(x) for x in dateline[3].split(":")]
timestamp = datetime(
year=date[2],
month=date[1],
day=date[0],
hour=time[0],
minute=time[1],
tzinfo=timezone.utc,
)
except Exception as e:
logging.warning(
f"Exception when obtaining date of eyjan.is article: {e}"
)
timestamp = None
if timestamp is None:
timestamp = _now()
# Extract the author name
author = "Ritstjórn eyjan.is"
metadata.heading = heading
metadata.author = author
metadata.timestamp = timestamp
return metadata
def get_content(self, soup: BeautifulSoup) -> Optional[Tag]:
"""Find the article content (main text) in the soup"""
# Delete div.container-fluid tags from the content
article = ScrapeHelper.div_class(soup, "article-full")
if article is None:
article = soup
if article is None:
logging.warning("No content for eyjan.is article")
return None
# Remove link to comments
result_soup = article.a
if result_soup is not None: