-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscrepe.py
More file actions
279 lines (209 loc) · 6.73 KB
/
screpe.py
File metadata and controls
279 lines (209 loc) · 6.73 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
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
__author__ = "Shane Drabing"
__license__ = "MIT"
__version__ = "0.0.8"
__email__ = "shane.drabing@gmail.com"
# IMPORTS
import concurrent.futures
import os
import pickle
import ssl
import time
import bs4
import requests
import selenium.webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait as WDW
from selenium.common.exceptions import NoSuchElementException
# CONSTANTS
# refresh rate
_PAUSE = 1 / 60
# webdriver methods
_BY_SELECTOR = selenium.webdriver.common.by.By.CSS_SELECTOR
_BY_XPATH = selenium.webdriver.common.by.By.XPATH
# user agent headers
_UA_MOZ = "Mozilla/5.0 (Windows NT 5.1; rv:52.0) Gecko/20100101 Firefox/103.0"
_HEADERS_MOZ = {"User-Agent": _UA_MOZ}
# CLASSES
class Screpe:
# ATTRIBUTES
Keys = Keys
# STATIC METHODS
@staticmethod
def node_text(node):
"""Given a bs4.Tag, get the text content in a pretty way.
>>> node = soup.select_one("h1")
>>> node_text(node)
'spam eggs and ham'
"""
if node is None:
return
return " ".join(node.get_text(" ").split())
@staticmethod
def get(url):
resp = requests.get(url, headers=_HEADERS_MOZ)
if resp.status_code != 200:
return
return resp.content
@staticmethod
def cook(html):
if html is None:
return
return bs4.BeautifulSoup(html, "lxml")
@staticmethod
def thread(f, *args):
with concurrent.futures.ThreadPoolExecutor() as exe:
return list(exe.map(f, *args))
@staticmethod
def wait_until(f, limit=10):
start = time.time()
while not f():
if start + limit < time.time():
raise RuntimeError(f"Timeout waiting for {f.__name__}")
time.sleep(_PAUSE)
# INTIALIZATION
def __init__(self, is_caching=True):
# user parameters
self.is_caching = bool(is_caching)
# essential attributes
self.driver = None
self.cache = dict()
# minor attributes
self._id = None
self._node = None
self._halt = 0
self._time = 0
def __del__(self):
self.driver_close()
# METHODS (RATE-LIMITING)
def halt(self):
while time.time() < self._time + self._halt:
time.sleep(_PAUSE)
self._time = time.time()
def halt_duration(self, seconds):
self._halt = max(0, float(seconds))
# METHODS (CACHE)
def cache_on(self):
self.is_caching = True
def cache_off(self):
self.is_caching = False
def cache_clear(self):
self.cache = dict()
def cache_save(self, fpath):
tmp = {
k[0]: self.cache[k]
for k in self.cache
if k[0] != "bs4"
}
with open(fpath, "wb") as fh:
pickle.dump(tmp, fh)
def cache_load(self, fpath, activate=True):
if activate:
self.cache_on()
with open(fpath, "rb") as fh:
self.cache = pickle.load(fh)
def cache_access(self, key, expr):
# check to see if we are caching
if not self.is_caching:
return expr()
# run the expression if not in cache
if key not in self.cache:
value = expr()
if value is None:
return
self.cache[key] = value
return self.cache[key]
# METHODS (BASE SELENIUM)
def driver_launch(self):
# lazy import
if "webdriver_manager" not in globals():
import webdriver_manager.firefox
# silent logging
os.environ["WDM_LOG_LEVEL"] = "0"
# options
opts = selenium.webdriver.firefox.options.Options()
opts.add_argument("--headless")
# install driver
gdm = webdriver_manager.firefox.GeckoDriverManager
path = gdm(print_first_line=False).install()
# assign driver to instance
self.driver = selenium.webdriver.Firefox(
executable_path=path, options=opts)
def driver_close(self):
if self.driver is not None:
self.driver.close()
def driver_restart(self):
self.driver_close()
self.driver_launch()
def driver_id(self):
return self.driver.find_element(_BY_XPATH, "html").id
def driver_loaded(self):
return self._id != self.driver_id()
# FUNCTIONS (BROWSING)
def open(self, url):
if self.driver is None:
self.driver_launch()
self.halt()
self.bide(lambda: self.driver.get(url))
def source(self):
if self.driver is None:
return
return self.cook(self.driver.page_source)
def bide(self, expr):
self._id = self.driver_id()
expr()
self.wait_until(self.driver_loaded)
def select(self, selector):
try:
self._node = self.driver.find_element(_BY_SELECTOR, selector)
return self._node
except NoSuchElementException:
pass
def wait_and_select(self, selector):
def f():
node = self.select(selector)
if node is None:
time.sleep(_PAUSE)
return False
return True
self.wait_until(f)
return self.select(selector)
def click(self, selector):
self._node = self.select(selector)
self._node.click()
return self._node
def send_keys(self, message):
if self._node is not None:
self._node.send_keys(message)
def send_enter(self):
self.send_keys(Keys.ENTER)
def send_tab(self):
self.send_keys(Keys.TAB)
# METHODS (REQUESTING)
def browse(self, url):
self.open(url)
return self.source()
def browse_many(self, urls):
return list(map(self.browse, urls))
def dine(self, url):
expr = lambda: self.halt() or self.get(url)
content = self.cache_access(("requests", url), expr)
soup = self.cache_access(("bs4", url), lambda: self.cook(content))
return soup
def dine_many(self, urls):
return self.thread(self.dine, urls)
def download(self, url, fpath):
expr = lambda: self.halt() or self.get(url)
content = self.cache_access(("requests", url), expr)
if content is None:
return
with open(fpath, "wb") as fh:
fh.write(content)
def download_table(self, url, fpath, which=0, index=False):
# lazy import
if "pandas" not in globals():
ssl._create_default_https_context = ssl._create_unverified_context
import pandas
self.halt()
dfs = pandas.read_html(url)
dfs[which].to_csv(fpath, index=index)