-
Notifications
You must be signed in to change notification settings - Fork 0
/
scriptparser.py
232 lines (173 loc) · 5.99 KB
/
scriptparser.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
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
# %%
## Importing packages
import numpy as np
import pandas as pd
import requests
import re
import os
import sys
from pathlib import Path
import shutil
import codecs
import time
import pickle
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# %%
## Reading pickle
open_file = open('pickles/movies_df.pkl', "rb")
movies_df = pickle.load(open_file)
# %%
## Parser parameters
temp_dir = 'data/temp/'
scripts_dir = 'data/scripts/'
parser_formats = ['html','.htm']
download_formats = ['.txt','.pdf','.rtf','.doc']
# %%
def get_temp_file_name():
temp_files = os.walk(temp_dir)
file_name = [a for a in temp_files][0][2][0]
file_path = temp_dir+file_name
p = Path(file_path)
file_suffix = p.suffix
file_stem = p.stem
return file_stem, file_suffix
# %%
def clear_dir(dir):
for root, _, files in os.walk(dir):
for f in files:
os.remove(os.path.join(root, f))
# %%
def wget_file(i, script_link):
try:
os.system(f"wget -P {temp_dir} \"{script_link}\"")
temp_file_stem, temp_file_suffix = get_temp_file_name()
if temp_file_suffix.lower() in download_formats:
file_move(i)
result = 'success'
else:
clear_dir(temp_dir)
result = 'fail'
except Exception as e:
result = 'fail'
print(f"Failed to wget {script_link}: {e}")
return result
# %%
def downloads_complete(driver):
if not driver.current_url.startswith("chrome://downloads"):
driver.get("chrome://downloads/")
return driver.execute_script("""
var items = document.querySelector('downloads-manager')
.shadowRoot.getElementById('downloadsList').items;
if (items.every(e => e.state === "COMPLETE"))
return items.map(e => e.fileUrl || e.file_url);
""")
# %%
def selenium_dl(i, script_link):
driver_path = "other/chromedriver"
options = webdriver.ChromeOptions()
options.add_experimental_option('prefs', {
"download.default_directory": temp_dir,
"download.prompt_for_download": False,
"download.directory_upgrade": True,
"plugins.always_open_pdf_externally": True
})
driver = webdriver.Chrome(options=options, executable_path=driver_path)
try:
driver.get(script_link)
# waits for all the files to be completed and returns the paths
download_wait = WebDriverWait(driver, 10, 1).until(downloads_complete)
temp_file_stem, temp_file_suffix = get_temp_file_name()
if temp_file_suffix in download_formats:
file_move(i)
result = 'success'
else:
clear_dir(temp_dir)
result = 'fail'
except Exception as e:
clear_dir(temp_dir)
result = 'fail'
print(f"Failed to selenium_dl {script_link}: {e}")
finally:
driver.quit()
return result
# %%
def parser(i, script_link):
driver_path = "other/chromedriver"
driver = webdriver.Chrome(executable_path=driver_path)
try:
driver.get(script_link)
body = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, 'html/body'))
)
#driver.find_element_by_xpath("html/body")
with open(f"{scripts_dir}/{i}.txt", "w") as text_file:
text_file.write(body.text)
except Exception as e:
clear_dir(temp_dir)
result = 'fail'
print(f"Failed to parse {script_link}: {e}")
finally:
driver.quit()
# %%
def file_move(i):
try:
temp_files = os.walk(temp_dir)
for temp_file in temp_files:
file_name = temp_file[2][0]
file_path = temp_dir+file_name
p = Path(file_path)
file_suffix = p.suffix
new_path = scripts_dir+str(i)+file_suffix
shutil.move(file_path, new_path)
result = 'success'
except Exception as e:
result = 'fail'
print(f"Failed to move {file_path}: {e}")
return result
# %%
## Main script for downloading
log = []
for i, script_link in enumerate(movies_df['script_link']): # range(2150,2176):
if i not in txtdir:
print(f"Starting the download of {i}")
if script_link[-4:].lower() in parser_formats:
result = parser(i, script_link)
if result == 'fail':
log.append([i, script_link, 'parser', 'fail'])
else:
log.append([i, script_link, 'parser', 'success'])
elif script_link[-4:].lower() in download_formats:
result = wget_file(i, script_link)
if result == 'fail':
log.append([i, script_link, 'wget_file', 'fail'])
result = selenium_dl(i, script_link)
if result == 'fail':
log.append([i, script_link, 'selenium_dl', 'fail'])
else:
log.append([i, script_link, 'selenium_dl', 'success'])
else:
log.append([i, script_link, 'wget_file', 'success'])
elif re.search(r'beingcharliekaufman',script_link,re.IGNORECASE):
result = selenium_dl(i, script_link)
if result == 'fail':
log.append([i, script_link, 'selenium_dl', 'fail'])
else:
log.append([i, script_link, 'selenium_dl', 'success'])
elif re.search(r'sfy',script_link,re.IGNORECASE):
result = parser(i, script_link)
if result == 'fail':
log.append([i, script_link, 'parser', 'fail'])
else:
log.append([i, script_link, 'parser', 'success'])
else:
log.append([i, script_link, 'other', 'left_out'])
log_df = pd.DataFrame(log, columns = ['i','script_link','method','result'])
# %%
## Writing log to pickles
open_file = open('log_df.pkl', 'wb')
pickle.dump(log_df, open_file)
open_file.close()