Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

download_prep.py 14 KB

You have to be logged in to leave a comment. Sign In
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
  1. """
  2. This module contains functions that assist in downloading and archiving csvs from
  3. lendingclub (loan info and payment history). Selenium is used to download the files.
  4. Other helper functions take care of comparing to any previously downloaded csvs
  5. and archiving when necessary.
  6. TODOS:
  7. selenium can sometimes go too fast and miss some of the download options
  8. I currently get around this by explicitly pausing for 2 seconds near the
  9. problem areas, but should probably create a function to check downloading csvs
  10. with all options in dropdown list.
  11. """
  12. # %load ../../lendingclub/csv_dl_archiving/download_prep.py
  13. # driver download https://github.com/mozilla/geckodriver/releases
  14. # extracted geckodriver to /usr/local/bin in ubuntu
  15. import os
  16. # import stat
  17. from stat import S_ISDIR, ST_CTIME, ST_MODE
  18. import subprocess
  19. import sys
  20. import time
  21. from datetime import datetime
  22. # from shutil import copytree, rmtree
  23. import pause
  24. from selenium.webdriver import Chrome
  25. from selenium.webdriver.chrome import webdriver as chrome_webdriver
  26. from selenium.webdriver.support.ui import Select
  27. import user_creds.account_info as acc_info
  28. from lendingclub import config
  29. from selenium.webdriver.remote.webelement import WebElement
  30. def send_keys(el: WebElement, keys: str):
  31. for i in range(len(keys)):
  32. el.send_keys(keys[i])
  33. pause.milliseconds(200)
  34. # import to grab user_creds
  35. sys.path.append(config.prj_dir)
  36. class DriverBuilder():
  37. '''
  38. helps build chrome driver
  39. https://stackoverflow.com/questions/45631715/downloading-with-chrome-headless-and-selenium
  40. '''
  41. def get_driver(self, download_location=None, headless=False):
  42. '''
  43. helps get driver
  44. '''
  45. driver = self._get_chrome_driver(download_location, headless)
  46. driver.set_window_size(1400, 700)
  47. return driver
  48. def _get_chrome_driver(self, download_location, headless):
  49. '''
  50. Makes the driver with right options
  51. '''
  52. chrome_options = chrome_webdriver.Options()
  53. if download_location:
  54. prefs = {
  55. 'download.default_directory': download_location,
  56. 'download.prompt_for_download': False,
  57. 'download.directory_upgrade': True,
  58. 'safebrowsing.enabled': False,
  59. 'safebrowsing.disable_download_protection': True
  60. }
  61. chrome_options.add_experimental_option('prefs', prefs)
  62. chrome_options.add_argument("--no-sandbox")
  63. if headless:
  64. chrome_options.add_argument("--headless")
  65. driver_path = '/usr/bin/chromedriver'
  66. if sys.platform.startswith("win"):
  67. driver_path += ".exe"
  68. driver = Chrome(executable_path=driver_path,
  69. chrome_options=chrome_options)
  70. if headless:
  71. self.enable_download_in_headless_chrome(driver, download_location)
  72. return driver
  73. def enable_download_in_headless_chrome(self, driver, download_dir):
  74. """
  75. there is currently a "feature" in chrome where
  76. headless does not allow file download:
  77. https://bugs.chromium.org/p/chromium/issues/detail?id=696481
  78. This method is a hacky work-around until the official chromedriver support for this.
  79. Requires chrome version 62.0.3196.0 or above.
  80. """
  81. # add missing support for chrome "send_command" to selenium webdriver
  82. driver.command_executor._commands["send_command"] = (
  83. "POST", '/session/$sessionId/chromium/send_command')
  84. params = {
  85. 'cmd': 'Page.setDownloadBehavior',
  86. 'params': {
  87. 'behavior': 'allow',
  88. 'downloadPath': download_dir
  89. }
  90. }
  91. command_result = driver.execute("send_command", params)
  92. print("response from browser:")
  93. for key in command_result:
  94. print("result:" + key + ":" + str(command_result[key]))
  95. def get_screenshot(driver):
  96. now = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
  97. driver.get_screenshot_as_file('screenshot-%s.png' % now)
  98. def download_csvs(download_path, pause_len=3000, debug=False):
  99. '''
  100. downloads all loan_info csvs and pmt_history csv
  101. '''
  102. print('attempting to download csvs to {0}'.format(os.path.abspath(download_path)))
  103. try:
  104. # setup constants
  105. email = acc_info.lc_dl_email_throwaway
  106. password = acc_info.lc_dl_pw_throwaway
  107. url_dl = "https://www.lendingclub.com/info/download-data.action"
  108. url_signin = "https://www.lendingclub.com/auth/login"
  109. url_pmt_hist = "https://www.lendingclub.com/site/additional-statistics"
  110. d_builder = DriverBuilder()
  111. driver = d_builder.get_driver(download_location=download_path,
  112. headless=True)
  113. # sign in
  114. driver.get(url_signin)
  115. pause.milliseconds(pause_len)
  116. email_box = driver.find_element_by_name('email')
  117. password_box = driver.find_element_by_name('password')
  118. email_box.send_keys(email)
  119. if debug:
  120. get_screenshot(driver)
  121. password_box.send_keys(password)
  122. if debug:
  123. get_screenshot(driver)
  124. # button = driver.find_element_by_xpath(
  125. # '/html/body/div[2]/div[1]/div[2]/form[1]/button')
  126. button = driver.find_element_by_class_name('form-button--submit')
  127. button.click()
  128. pause.milliseconds(pause_len)
  129. # download loan_info
  130. driver.get(url_dl)
  131. # download_btn = driver.find_element_by_xpath(
  132. # '//*[@id="currentLoanStatsFileName"]')
  133. download_btn = driver.find_element_by_id(
  134. 'currentLoanStatsFileNameHandler')
  135. select = driver.find_element_by_xpath(
  136. '//*[@id="loanStatsDropdown"]') # get the select element
  137. options = select.find_elements_by_tag_name(
  138. "option") # get all the options into a list
  139. options_dict = {}
  140. for option in options: # iterate over the options, place attribute value in list
  141. options_dict[option.get_attribute("value")] = option.text
  142. for opt_val, text in options_dict.items():
  143. print("starting download on option {0}, {1}".format(opt_val, text))
  144. select = driver.find_element_by_xpath(
  145. '//*[@id="loanStatsDropdown"]')
  146. # print('found the select dropdown')
  147. selection = Select(select)
  148. selection.select_by_value(opt_val)
  149. # print('set selection to option value {0}: {1}'.format(opt_val, text))
  150. download_btn.click()
  151. pause.milliseconds(pause_len)
  152. # print('got to click download btn')
  153. # now = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
  154. # driver.get_screenshot_as_file('screenshot-%s.png'%now)
  155. # setup to workaround the center-block button:
  156. try:
  157. blocking_btn = driver.find_element_by_class_name(
  158. 'center-block')
  159. blocking_btn.click()
  160. close_btn = driver.find_element_by_class_name('close')
  161. close_btn.click()
  162. # print('got through blocking data disclaimer')
  163. except:
  164. # print('did not get through blocking data disclaimer')
  165. pass
  166. pause.milliseconds(pause_len)
  167. # payment history downloads
  168. pause.milliseconds(pause_len)
  169. driver.get(url_pmt_hist)
  170. pause.milliseconds(pause_len)
  171. pmt_history = driver.find_element_by_partial_link_text('All payments')
  172. pmt_history.click()
  173. # wait for all downloads to finish
  174. while True:
  175. if len(os.listdir(download_path)) != (
  176. len(options_dict) + 1): # +1 for one pmt history file
  177. time.sleep(5)
  178. print('waiting for all csv downloads to start')
  179. continue
  180. else:
  181. files = os.listdir(download_path)
  182. k = 0
  183. time.sleep(5)
  184. print('checking/waiting for all csv downloads to finish')
  185. for filename in files:
  186. if 'crdownload' in filename:
  187. print('{0} is still downloading'.format(filename))
  188. time.sleep(30)
  189. else:
  190. k += 1
  191. # print(k)
  192. if k == len(files):
  193. time.sleep(2)
  194. break
  195. print('done downloading')
  196. driver.close()
  197. return True
  198. except Exception as e:
  199. print(e)
  200. now = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
  201. driver.get_screenshot_as_file('screenshot-%s.png' % now)
  202. def get_hashes(path):
  203. '''
  204. gets shasum hashes for files to check for file changes
  205. '''
  206. print('computing shasum for files in {0}'.format(os.path.abspath(path)))
  207. hashes = {}
  208. files = os.listdir(path)
  209. for file_ in files:
  210. sha = subprocess.check_output('shasum -a 256 {0}\
  211. '.format(path + '/'
  212. + file_),
  213. shell=True)
  214. hashes[file_] = sha.split()[0]
  215. return hashes
  216. def check_file_changes(compare_dir, just_dled_hashes):
  217. '''
  218. Checks for sha differences for downloaded vs archived csvs
  219. '''
  220. need_to_clean = False
  221. print(
  222. 'starting to check for file changes comparing what was just downloaded.'
  223. )
  224. print('looking for previous downloads at {0}'.format(compare_dir))
  225. try:
  226. previous_dled_hashes = get_hashes(compare_dir[1])
  227. # compare new download to previous download
  228. # check for added or deleted files
  229. dne_files = set(just_dled_hashes.keys()).intersection(
  230. set(previous_dled_hashes.keys()))
  231. add_files = set(previous_dled_hashes.keys()).intersection(
  232. set(just_dled_hashes.keys()))
  233. if len(just_dled_hashes) != len(previous_dled_hashes):
  234. need_to_clean = True
  235. print("Compared to the previous time new csv's were downloaded, \
  236. the following files were deleted: \n {0}".format(
  237. dne_files))
  238. print("Compared to the previous time new csv's were downloaded, \
  239. the following files are new additions: \n {0}".format(
  240. add_files))
  241. else:
  242. print(
  243. 'No files were added or deleted since previous downloading of csvs'
  244. )
  245. # check for shasum256 changes
  246. changed_files = []
  247. for key in just_dled_hashes.keys() & previous_dled_hashes.keys():
  248. if previous_dled_hashes[key] != just_dled_hashes[key]:
  249. changed_files.append(key)
  250. if len(changed_files) == 0:
  251. print('There are no changes to previous downloaded lending club \
  252. csvs (loan_info and pmt_hist) via shasum256 hashes')
  253. else:
  254. need_to_clean = True
  255. print('Compared to the previous data download, the shasum256 \
  256. hashes changed for the following files: {0}'.format(changed_files))
  257. except IndexError:
  258. need_to_clean = True
  259. print('Could not find previously download directory? This is \
  260. probably your first time downloading the csvs or the \
  261. first download to a new path.')
  262. return need_to_clean
  263. def get_newest_creationtime_dir(ppath):
  264. '''returns path of newest dir by creation time in ppath'''
  265. print('getting folders sorted by creation time in {0}'.format(
  266. os.path.abspath(ppath)))
  267. csv_folders = [
  268. os.path.join(ppath, fn) for fn in os.listdir(ppath)
  269. if fn not in ['archived_csvs', 'working_csvs', 'latest_csvs']
  270. ]
  271. csv_folders = [(os.stat(path), path) for path in csv_folders]
  272. csv_folders = [(stat[ST_CTIME], path) for stat, path in csv_folders
  273. if S_ISDIR(stat[ST_MODE])]
  274. return sorted(csv_folders)[-1]
  275. # def archiver(archive_flag, ppath, archiver_dir=None):
  276. # '''will archive dirs if told to'''
  277. # archiver_dir = os.path.join(
  278. # os.path.expanduser('~'), 'projects', 'lendingclub', 'data', 'csvs',
  279. # 'archived_csvs') if not archiver_dir else archiver_dir
  280. # os.makedirs(archiver_dir, exist_ok=True)
  281. # if archive_flag:
  282. # just_dled = get_sorted_creationtime_dirs(ppath)[-1][1]
  283. # newest_folder = os.path.split(just_dled)[1]
  284. # copytree(just_dled, os.path.join(archiver_dir, newest_folder))
  285. # print('copied {0} to {1}'.format(newest_folder,
  286. # os.path.abspath(archiver_dir)))
  287. # def cleaner(ppath):
  288. # '''
  289. # cleans the ppath of every dir except archived_csvs
  290. # '''
  291. # just_dled = os.path.split(get_sorted_creationtime_dirs(ppath)[-1][1])[1]
  292. # keep_dirs = ['archived_csvs'] # , 'working_csvs', just_dled]
  293. # for tree in os.listdir(ppath):
  294. # if tree not in keep_dirs:
  295. # rmtree(os.path.join(ppath, tree), onerror=handle_error)
  296. # print('removing old dirs {0}'.format(tree))
  297. # return just_dled
  298. # def handle_error(func, path, exc_info):
  299. # '''
  300. # Error handler function
  301. # It will try to change file permission and call the calling function again,
  302. # From https://thispointer.com/python-how-to-delete-a-directory-recursively-using-shutil-rmtree/
  303. # '''
  304. # print('Handling Error for file ', path)
  305. # print(exc_info)
  306. # # Check if file access issue
  307. # if not os.access(path, os.W_OK):
  308. # print('Hello')
  309. # # Try to change the permision of file
  310. # os.chmod(path, stat.S_IWUSR)
  311. # # call the calling function again
  312. # func(path)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...