-
Notifications
You must be signed in to change notification settings - Fork 0
/
rss_parser.py
125 lines (105 loc) · 3.54 KB
/
rss_parser.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
"""
Type: Module
Developer: Vignesh
mail_id: vignesh@averyxgroup.com
Description: Scraping rss content from URL and contains support functions
"""
### scrapers
import feedparser
from bs4 import BeautifulSoup as bs
### utils
import datetime
from dateutil.parser import parse
from time import mktime
import regex as re
from werkzeug.urls import url_fix
class RSS_Parser:
def __init__(self):
self.feedparser = feedparser
self._remove_tags = ['img']
"""
Parsing XML document using feedparser
"""
def parse(self, url, last_poll, last_update, pattern):
try:
url = url_fix(url)
parsed_list = []
latest_update = last_update
feed = self.feedparser.parse(url)
if feed['entries']:
for entry in feed['entries']:
if 'published' in entry:
published = parse(entry['published'])
else:
published = parse(entry['pubDate'])
if published > latest_update:
latest_update = published
if published <= last_update:
continue
title = entry['title']
### key selection, refer rss_vs_atom.config in ./
if 'summary' in entry:
key = 'summary'
elif 'description' in entry:
key = 'description'
else:
key = 'content'
###
if pattern == [] or pattern[-1] == key:
summary = entry[key]
summary = bs(summary, 'html.parser')
summary = self.remove_tags(summary)
summary = self.remove_tags_regex(str(summary))
summary = self.clean_text(str(summary))
else:
summary = bs(entry[key], 'html.parser')
summary = self.remove_tags(summary)
for element in pattern[1:]:
summary = summary.find_all(element)[0]
summary = summary.text
summary = self.remove_tags_regex(summary)
record = {
"title": title,
"summary": summary,
"published": published,
}
parsed_list.append(record)
return parsed_list, latest_update
else:
return ["Reject"], None
except Exception as e:
self.log(e)
return ["Exception", e], None
"""
Removes unwanted tags from the summary
"""
def remove_tags(self, html):
for tag in self._remove_tags:
for element in html.select(tag):
element.extract()
return html
"""
Removes unwanted tags from summary using regex
"""
def remove_tags_regex(self, html):
compiled = re.compile(r'<.*?>')
html = compiled.sub('', html)
return html
"""
String cleaning operations
"""
def clean_text(self, text):
text = re.sub(r"^\W+|\W+$", '', text)
text = re.sub(r'[^\x00-\x7f]', '', text)
return text
"""
Exception Logger
"""
def log(self, e):
#print(e)
pass
"""
Validate RSS link
"""
def validate_link(self, feed):
pass