-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparsers.py
More file actions
63 lines (46 loc) · 1.45 KB
/
parsers.py
File metadata and controls
63 lines (46 loc) · 1.45 KB
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
import re
import lxml.html
from lxml.cssselect import CSSSelector
__author__ = 'ivanenko.danil'
class BaseParser(object):
"""
base clas for parsers, it saves selector in constructor
"""
def __init__(self, selector):
self.selector = selector
def search(self, text):
"""
get text and return result or empty string
"""
pass
class RegexParser(BaseParser):
"""
search text using regex selectors
"""
def __init__(self, selector):
super(RegexParser, self).__init__(selector)
# compile regex pattern here, so we do not waist time later
self.pattern = re.compile(self.selector)
def search(self, text):
match = self.pattern.search(text)
if match:
result = match.group(1)
else:
result = ""
return result
class CSSParser(BaseParser):
"""
search text using CSS selectors
"""
def search(self, text):
sel = CSSSelector(self.selector)
# grrrr... not good idea to parse html for every selector
tree = lxml.html.fromstring(text)
results = sel(tree)
if len(results) > 0:
# exclude parent tag, we save only its content
# also we record only first found tag, not all tags with selector
res = (results[0].text or '') + "".join([lxml.html.tostring(child) for child in results[0]])
else:
res = ""
return res