-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcongress_crawler.py
77 lines (49 loc) · 2.43 KB
/
congress_crawler.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
import requests
import json
import pymysql
class Mysql():
def __init__(self):
self.connection = pymysql.connect(host='172.20.167.148',
user='root',
password='password',
db='us_congress',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
def do_query(self, sql_string, data=None):
cursor = self.connection.cursor()
result_list = []
if 'select' in sql_string or 'SELECT' in sql_string:
cursor.execute(sql_string)
for r in cursor:
result_list.append(r)
print(result_list)
elif 'insert' in sql_string or 'INSERT' in sql_string:
cursor.execute(sql_string, data)
self.connection.commit()
else:
return 'Query Method not Allowed'
cursor.close()
self.connection.close()
class Populate():
def __init__(self):
self.all_congress_url = 'https://theunitedstates.io/congress-legislators/legislators-current.json'
def _get_infos(self, raw_data):
name = raw_data['name']['official_full']
latest_term_info = raw_data['terms'][len(raw_data['terms'])-1]
party = latest_term_info.get('party')
state = latest_term_info.get('state')
office_address = latest_term_info.get('address')
office_phone = latest_term_info.get('phone')
start_date = latest_term_info.get('start')
end_date = latest_term_info.get('end')
return [name, party, state, office_address, office_phone, start_date, end_date]
def handler(self):
all_congress = requests.get(self.all_congress_url)
json_all_congress = json.loads(all_congress.text)
for member in json_all_congress:
congress = self._get_infos(member)
sql = "INSERT INTO members (`name`, `party`, `state`, `office_address`, `office_phone`, `start_date`, `end_date`) VALUES (%s, %s, %s, %s, %s, %s, %s);"
Mysql().do_query(sql, (congress[0], congress[1], congress[2], congress[3], congress[4], congress[5], congress[6]))
Mysql().do_query( "SELECT * FROM develop.test" )
if __name__ == '__main__':
Populate().handler()