This repository has been archived by the owner on May 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
selector.py
106 lines (82 loc) · 2.61 KB
/
selector.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
import re
import dateparser
from pyquery import PyQuery
class SelectorType:
def __init__(self, selector):
self.selector = selector
def result(self, target):
return None
def result_text(self, target):
return None
class PyQuerySelectorType(SelectorType):
def result(self, target):
d = PyQuery(target)
return d(self.selector)
def result_text(self, target):
result = self.result(target)
return None if not result else result.text()
class XpathSelectorType(SelectorType):
def result(self, target):
return target.xpath(self.selector)
def result_text(self, target):
result = self.result(target)
if not result:
return None
try:
# Do your best
return result.text
except AttributeError:
return result[0]
_selector_types = {
'jquery': PyQuerySelectorType,
'xpath': XpathSelectorType,
'default': PyQuerySelectorType,
}
class Selector:
_optional = [
'regex',
'date_format',
]
def __init__(self, selector, multiple=False, is_date=False):
self.options = {}
if isinstance(selector, str):
self.selector = selector
self.SelectorType = _selector_types['default'](self.selector)
else:
self.selector = selector['selector']
for option in self._optional:
if option in selector:
self.options[option] = selector[option]
if 'selector_type' in selector:
self.SelectorType = _selector_types[
selector['selector_type']
](self.selector)
else:
self.SelectorType = _selector_types[
'default'
](self.selector)
self.multiple = multiple
self.is_date = is_date
def result(self, target):
if self.multiple:
return self.SelectorType.result(target)
result_text = self.SelectorType.result_text(target)
if 'regex' in self.options:
match = re.search(
self.options['regex'],
result_text,
)
if match:
result_text = match.groups('')[0]
if not self.is_date:
return result_text
args = {
'date_string': result_text,
'languages': ['en'],
}
if 'date_format' in self.options:
args['date_formats'] = [
self.options['date_format'],
]
result_text = dateparser.parse(**args)
return result_text