-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsample-parser.py
More file actions
75 lines (49 loc) · 1.81 KB
/
sample-parser.py
File metadata and controls
75 lines (49 loc) · 1.81 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
import os
import sys
import time
import json
import urllib.request
from bs4 import BeautifulSoup
import re
def get_last_statements(url):
r = urllib.request.urlopen(url).read()
soup = BeautifulSoup(r)
result = str(soup.find(text = re.compile('Offender:')).findNext('p').findNext('p').findNext('p').get_text().encode('utf-8'))
return result
def parse_rows(rows):
heads = []
results = []
a = 0
rows = rows[1:]
for row in rows:
table_data = row.find_all('td')
current_row = []
for data in table_data:
if(data.get_text() == "Last Statement"):
try:
current_row.append(get_last_statements('https://www.tdcj.state.tx.us/death_row/' + data.find_all('a', href=True)[0]['href']))
except:
current_row.append('This offender declined to make a last statement.')
print("OOPS!")
elif(data.get_text() == "Offender Information"):
pass
else:
current_row.append(data.get_text())
#current_row.append(data.get_text())
results.append(current_row)
print(str(a) +' of ' + str(len(rows)))
a+=1
return heads,results
def createJSON(values):
keys = ['Exectution', 'Last Statement', 'Last Name', 'First Name', 'TDCJ Number', "Age", 'Date', 'Race', 'County']
return [dict(zip(keys, i)) for i in values]
r = urllib.request.urlopen('https://www.tdcj.state.tx.us/death_row/dr_executed_offenders.html').read()
soup = BeautifulSoup(r)
table = soup.find('table')
rows = table.find_all('tr')
table_heads, table_data = parse_rows(rows)
myJSON = createJSON(table_data)
print(table_data)
print(myJSON)
with open('data.txt', 'w') as outfile:
json.dump(myJSON, outfile)