-
Notifications
You must be signed in to change notification settings - Fork 2
/
crawl.py
233 lines (191 loc) · 7.68 KB
/
crawl.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
233
import argparse
import yaml
import pandas as pd
import os
import json
import subprocess
from datetime import datetime
import re
import logging
from multiprocessing.pool import ThreadPool
from selenium import webdriver
from xvfbwrapper import Xvfb
logging.basicConfig(level=logging.DEBUG)
def usage():
print("Usage")
print("crawl -c config.yaml")
def parseArguments():
parser = argparse.ArgumentParser(description="Process some integers.")
parser.add_argument("-c", "--config", type=str, help="config file")
args = parser.parse_args()
return args
def carbonResults(url):
try:
url = url.replace(r"http://", "").replace(r"https://", "")
url = "https://" + url
logging.info(url)
res = subprocess.run(["node", "carbon.js", url], capture_output=True, text=True)
ret = json.loads(res.stdout)
ret["url"] = url
return ret
except (subprocess.SubprocessError, json.JSONDecodeError, AttributeError):
try:
url = url.replace(r"http://", "").replace(r"https://", "")
url = "http://" + url
logging.info(url)
res = subprocess.run(
["node", "carbon.js", url], capture_output=True, text=True
)
ret = json.loads(res.stdout)
ret["url"] = url
return ret
except (subprocess.SubprocessError, json.JSONDecodeError, AttributeError):
logging.error("Error {}".format(url))
return {"lighthouse": "Error", "score": 0, "url": url}
def checkBootstrap(url):
try:
url = url.replace(r"http://", "").replace(r"https://", "")
url = "https://" + url
logging.info(url)
res = subprocess.run(
["node", "checkBootstrap.js", url], capture_output=True, text=True
)
ret = json.loads(res.stdout)
ret["url"] = url
except (subprocess.SubprocessError, json.JSONDecodeError, AttributeError) as e:
logging.debug("stdout {}".format(res.stdout))
logging.debug(e)
try:
url = url.replace(r"http://", "").replace(r"https://", "")
url = "http://" + url
logging.info(url)
res = subprocess.run(
["node", "checkBootstrap.js", url], capture_output=True, text=True
)
ret = json.loads(res.stdout)
ret["url"] = url
except (subprocess.SubprocessError, json.JSONDecodeError, AttributeError) as e:
logging.debug(e)
logging.debug("stdout {}".format(res.stdout))
logging.error("Error {}".format(url))
return {"bootstrap": "Error", "url": url}
bootstrapGen = False
bootstrapItalia = False
for (k, e) in ret.items():
if re.match(r".*(js|css)$", k, re.IGNORECASE):
logging.debug("key {} matches".format(k))
if re.match(
r".*bootstrap.{0,16}italia.*", "{}".format(k), re.IGNORECASE
) or re.match(r".*bootstrap.{0,16}italia.*", "{}".format(e), re.IGNORECASE):
bootstrapItalia = True
if re.match(r".*bootstrap.*", "{}".format(k), re.IGNORECASE) or re.match(
r".*bootstrap.*", "{}".format(e), re.IGNORECASE
):
bootstrapGen = True
ret = {"bootstrap": bootstrapGen, "bootstrapItalia": bootstrapItalia}
return ret
def checkBootstrap2(url):
ret={}
with Xvfb() as xvfb:
webdrv = webdriver.Firefox()
try:
url = url.replace(r"http://", "").replace(r"https://", "")
url = "https://" + url
logging.info("checkBootstrap2 {}".format(url))
webdrv.get(url)
ret["url"] = url
ret["bootstrapItaliaVariable"]=webdrv.execute_script('return window.BOOTSTRAP_ITALIA_VERSION;')
ret["bootstrapItaliaMethod"]=webdrv.execute_script('return getComputedStyle(document.body).getPropertyValue("--bootstrap-italia-version");')
except Exception as e:
logging.debug(e)
try:
url = url.replace(r"http://", "").replace(r"https://", "")
url = "http://" + url
logging.info("checkBootstrap2 {}".format(url))
webdrv.get(url)
ret["url"] = url
ret["bootstrapItaliaVariable"]=webdrv.execute_script('return window.BOOTSTRAP_ITALIA_VERSION;')
ret["bootstrapItaliaMethod"]=webdrv.execute_script('return getComputedStyle(document.body).getPropertyValue("--bootstrap-italia-version");')
except Exception as e:
logging.debug(e)
ret["url"] = url
ret["bootstrapItaliaVariable"]=None
ret["bootstrapItaliaMethod"]=None
return ret
def crawlComune(comune, outputDir, cfg):
logging.info("crawlComune {}".format(comune["Denominazione_ente"]))
tsNow = datetime.now().timestamp()
codiceIPA = comune["Codice_IPA"]
rerun = True
with open(os.path.join(outputDir, codiceIPA + ".json"), "a+") as f:
try:
f.seek(0)
existData = json.load(f)
ts = existData["ts"]
logging.info(
"tsNow {} ts {} diff {} TTL {}".format(
tsNow, ts, tsNow - ts, cfg["TTL"]
)
)
if (tsNow - ts) < cfg["TTL"]:
rerun = False
except json.JSONDecodeError:
logging.warning("Cannot decode JSON")
pass
if rerun:
carbonRes = carbonResults(comune["Sito_istituzionale"])
del carbonRes["rawResult"]["audits"]["screenshot-thumbnails"]
del carbonRes["rawResult"]["audits"]["final-screenshot"]
del carbonRes["rawResult"]["audits"]["full-page-screenshot"]
res = None
try:
res = {
"Codice_IPA": codiceIPA,
"ts": tsNow,
"url": carbonRes["url"],
"lighthouseScore": carbonRes["score"],
"first-meaningful-paint": carbonRes["rawResult"]["audits"][
"first-meaningful-paint"
],
"total-byte-weight": carbonRes["rawResult"]["audits"][
"total-byte-weight"
],
"resource-summary": carbonRes["rawResult"]["audits"][
"resource-summary"
],
"accessibility": carbonRes["rawResult"]["categories"]["accessibility"]["score"],
"lighthouseRawResult": carbonRes["rawResult"],
}
except KeyError:
print("Error carbonRes", carbonRes)
bootstrapRes = checkBootstrap(comune["Sito_istituzionale"])
res["bootstrapItalia"] = bootstrapRes
bootstrapRes2 = checkBootstrap2(comune["Sito_istituzionale"])
res["bootstrapItalia2"] = bootstrapRes2
if res is not None:
print(res)
f.seek(0)
f.truncate(0)
json.dump(res, f)
def main():
args = parseArguments()
with open(args.config, "r") as f:
cfg = yaml.safe_load(f)
logging.info(cfg)
crawlList = pd.read_csv(cfg["list"])
comuniList = crawlList[crawlList["Codice_natura"] == 2430]
# Randomize list
comuniList = comuniList.sample(frac=1).reset_index(drop=True)
outputDir = cfg["outputDir"]
try:
os.mkdir(outputDir)
except OSError:
pass
tp = ThreadPool()
for idx, comune in comuniList.iterrows():
tp.apply_async(crawlComune, (comune, outputDir, cfg))
#crawlComune(comune, outputDir, cfg)
tp.close()
tp.join()
if __name__ == "__main__":
main()