This repository has been archived by the owner on Oct 28, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
scraper.py
75 lines (67 loc) · 2.72 KB
/
scraper.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
#!/usr/bin/python
import requests, json, time, urllib
from bs4 import BeautifulSoup
class Seattle911IncidentProcessor:
def __init__(self, processor):
self.RECORDS_URL = 'http://www2.ci.seattle.wa.us/fire/realtime911/getRecsForDatePub.asp?action=Today&incDate=&rad1=des'
self.processor = processor
pass
def parse_incidents(self):
soup = BeautifulSoup(requests.get(self.RECORDS_URL).content)
rows = soup.find_all('table')[3].find_all('tr')
incidents = []
for row in rows:
try:
tds = row.find_all("td")
a = {}
if len(tds[0].contents) > 0:
a['date'] = tds[0].contents[0]
else:
a['date'] = "Unknown"
print("Date missing!")
if len(tds[1].contents) > 0:
a['number'] = tds[1].contents[0]
else:
a['number'] = "Unknown"
print("Incident number missing!")
if len(tds[2].contents) > 0:
a['level'] = tds[2].contents[0]
else:
a['level'] = "Unknown"
print("Level missing for incident %s" % a['number'])
if len(tds[3].contents) > 0:
a['units'] = tds[3].contents[0]
else:
a['units'] = "Unknown"
print("Units missing for incident %s" % a['number'])
if len(tds[4].contents) > 0:
a['location'] = tds[4].contents[0]
else:
a['location'] = "Unknown"
print("Location missing for incident %s" % a['number'])
if len(tds[5].contents) > 0:
a['type'] = tds[5].contents[0]
else:
a['type'] = "Unknown"
print("Type missing for incident %s" % a['number'])
incidents.append(a)
except IndexError:
print(row.prettify())
return incidents
def process_incidents(self, incidents):
try:
recorded = json.load(open('incidents.json'))
except Exception as inst:
recorded = []
try:
for incident in incidents:
if not incident['number'] in recorded:
self.processor.process(incident)
self.save_state(recorded)
except Exception as e:
print("Caught Exception: " + str(e))
self.save_state(recorded)
def save_state(self, incidents):
savefile = open('incidents.json', 'w')
savefile.write(json.dumps(incidents))
savefile.close()