-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathRequest.py
106 lines (73 loc) · 3.09 KB
/
Request.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
import json
import io
import requests
# Open file to write output to.
test2 = io.open("test2.csv", "w", encoding='utf8')
test2.write("Name, ID, Type, Phone, Location, Price, Closed, Rating, Website \n")
# Got a list of all zip codes in VA from post office website.
zip_codes = []
zips = open("/ZipCodes.txt", "r")
code = zips.readline()
while code != "":
code = code.split()
zip_codes.append(code[0])
code = zips.readline()
# Make requests for all zip codes.
for zip_code in zip_codes:
app_id = '******'
app_secret = '**********'
data = {'grant_type': 'client_credentials',
'client_id': app_id,
'client_secret': app_secret}
token = requests.post('https://api.yelp.com/oauth2/token', data=data)
access_token = token.json()['access_token']
url = 'https://api.yelp.com/v3/businesses/search'
headers = {'Authorization': 'bearer %s' % access_token}
params = {'location': zip_code, 'categories':'restaurants'
}
resp = requests.get(url=url, params=params, headers=headers)
import pprint
#pprint.pprint(resp.json()['businesses'])
# This part puts the output into a new file in csv format. The order is:
# Name, ID, Type, Phone, Address, Price, Closed? Rating and URL
for string in resp.json()['businesses']:
name, ID, Type, phone, add, price, closed, rating, url = "null", "null", "null", "null", "null", "null", "null", "null", "null"
if "name" in string:
name = string['name'].strip()
name = name.replace(',', "")
if "id" in string:
ID = string['id'].strip()
ID = ID.replace(',', "")
if "categories" in string:
if len(string['categories']) > 0:
if "alias" in string['categories'][0]:
Type = string['categories'][0]['alias']
if "display_phone" in string:
phone = string['display_phone']
if phone == " " or phone == "":
phone = "null"
if "location" in string:
if "display_address" in string['location']:
add = ""
for i in range(len(string['location']['display_address'])):
add = add + string['location']['display_address'][i].strip() + " "
add = add.replace(',', "")
print(add)
if 'price' in string:
price = string['price']
if "is_closed" in string:
closed = str(string['is_closed'])
if "rating" in string:
rating = str(string['rating'])
if "url" in string:
url = string['url']
test2.write(name + ', ')
test2.write(ID + ', ')
test2.write(Type + ', ')
test2.write(phone + ', ')
test2.write(add + ', ')
test2.write(price + ', ')
test2.write(closed + ', ')
test2.write(rating + ', ')
test2.write(url + '\n')
test2.close()