forked from tomslee/airbnb-data-collection
-
Notifications
You must be signed in to change notification settings - Fork 0
/
airbnb.py
executable file
·484 lines (457 loc) · 19.4 KB
/
airbnb.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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
#!/usr/bin/python3
# ============================================================================
# Airbnb web site scraper, for analysis of Airbnb listings
# Tom Slee, 2013--2015.
#
# function naming conventions:
# ws_get = get from web site
# db_get = get from database
# db_add = add to the database
#
# function name conventions:
# add = add to database
# display = open a browser and show
# list = get from database and print
# print = get from web site and print
# ============================================================================
import logging
import argparse
import sys
import time
import requests
from lxml import html
from datetime import datetime
import psycopg2
import psycopg2.errorcodes
import webbrowser
from airbnb_config import ABConfig
from airbnb_survey import ABSurvey, ABSurveyByBoundingBox
from airbnb_survey import ABSurveyByNeighborhood, ABSurveyByZipcode
from airbnb_listing import ABListing
import airbnb_ws
# ============================================================================
# CONSTANTS
# ============================================================================
# Script version
# 3.0 modified -sb searches to reflect new Airbnb web site design (Jan 2018)
# 2.9 adds resume for bounding box searches. Requires new schema
# 2.8 makes different searches subclasses of ABSurvey
# 2.7 factors the Survey and Listing objects into their own modules
# 2.6 adds a bounding box search
# 2.5 is a bit of a rewrite: classes for ABListing and ABSurvey, and requests lib
# 2.3 released Jan 12, 2015, to handle a web site update
SCRIPT_VERSION_NUMBER = 3.0
logger = logging.getLogger()
def list_search_area_info(config, search_area):
try:
conn = config.connect()
cur = conn.cursor()
cur.execute("""
select search_area_id
from search_area where name=%s
""", (search_area,))
result_set = cur.fetchall()
cur.close()
count = len(result_set)
if count == 1:
print("\nThere is one search area called",
str(search_area),
"in the database.")
elif count > 1:
print("\nThere are", str(count),
"cities called", str(search_area),
"in the database.")
elif count < 1:
print("\nThere are no cities called",
str(search_area),
"in the database.")
sys.exit()
sql_neighborhood = """select count(*) from neighborhood
where search_area_id = %s"""
sql_search_area = """select count(*) from search_area
where search_area_id = %s"""
for result in result_set:
search_area_id = result[0]
cur = conn.cursor()
cur.execute(sql_neighborhood, (search_area_id,))
count = cur.fetchone()[0]
cur.close()
print("\t" + str(count) + " neighborhoods.")
cur = conn.cursor()
cur.execute(sql_search_area, (search_area_id,))
count = cur.fetchone()[0]
cur.close()
print("\t" + str(count) + " Airbnb cities.")
except psycopg2.Error as pge:
logger.error(pge.pgerror)
logger.error("Error code " + pge.pgcode)
logger.error("Diagnostics " + pge.diag.message_primary)
cur.close()
conn.rollback()
raise
except Exception:
logger.error("Failed to list search area info")
raise
def list_surveys(config):
try:
conn = config.connect()
cur = conn.cursor()
cur.execute("""
select survey_id, to_char(survey_date, 'YYYY-Mon-DD'),
survey_description, search_area_id, status
from survey
where survey_date is not null
and status is not null
and survey_description is not null
order by survey_id asc""")
result_set = cur.fetchall()
if len(result_set) > 0:
template = "| {0:3} | {1:>12} | {2:>50} | {3:3} | {4:3} |"
print(template.format("ID", "Date", "Description", "SA", "status"))
for survey in result_set:
(survey_id, survey_date, desc, sa_id, status) = survey
print(template.format(survey_id, survey_date, desc, sa_id, status))
except Exception:
logger.error("Cannot list surveys.")
raise
def db_ping(config):
try:
conn = config.connect()
if conn is not None:
print("Connection test succeeded")
else:
print("Connection test failed")
except Exception:
logger.exception("Connection test failed")
def db_add_survey(config, search_area):
try:
conn = config.connect()
cur = conn.cursor()
# Add an entry into the survey table, and get the survey_id
sql = """
insert into survey (survey_description, search_area_id)
select (name || ' (' || current_date || ')') as survey_description,
search_area_id
from search_area
where name = %s
returning survey_id"""
cur.execute(sql, (search_area,))
survey_id = cur.fetchone()[0]
# Get and print the survey entry
cur.execute("""select survey_id, survey_date,
survey_description, search_area_id
from survey where survey_id = %s""", (survey_id,))
(survey_id,
survey_date,
survey_description,
search_area_id) = cur.fetchone()
conn.commit()
cur.close()
print("\nSurvey added:\n" +
"\n\tsurvey_id=" + str(survey_id) +
"\n\tsurvey_date=" + str(survey_date) +
"\n\tsurvey_description=" + survey_description +
"\n\tsearch_area_id=" + str(search_area_id))
except Exception:
logger.error("Failed to add survey for " + search_area)
raise
def db_get_room_to_fill(config, survey_id):
for attempt in range(config.MAX_CONNECTION_ATTEMPTS):
try:
conn = config.connect()
cur = conn.cursor()
if survey_id == 0: # no survey specified
sql = """
select room_id, survey_id
from room
where deleted is null
order by random()
limit 1
"""
cur.execute(sql)
else:
sql = """
select room_id, survey_id
from room
where deleted is null
and survey_id = %s
order by random()
limit 1
"""
cur.execute(sql, (survey_id,))
(room_id, survey_id) = cur.fetchone()
listing = ABListing(config, room_id, survey_id)
cur.close()
conn.commit()
return listing
except TypeError:
logger.info("Finishing: no unfilled rooms in database --")
conn.rollback()
del (config.connection)
return None
except Exception:
logger.exception("Error retrieving room to fill from db")
conn.rollback()
del (config.connection)
return None
def ws_get_city_info(config, city, flag):
try:
url = config.URL_SEARCH_ROOT + city
response = airbnb_ws.ws_request_with_repeats(config, url)
if response is None:
return False
tree = html.fromstring(response.text)
try:
citylist = tree.xpath(
"//input[@name='location']/@value")
neighborhoods = tree.xpath(
"//input[contains(@id, 'filter-option-neighborhoods')]/@value")
if flag == config.FLAGS_PRINT:
print("\n", citylist[0])
print("Neighborhoods:")
for neighborhood in neighborhoods:
print("\t", neighborhood)
elif flag == config.FLAGS_ADD:
if len(citylist) > 0:
conn = config.connect()
cur = conn.cursor()
# check if it exists
sql_check = """
select name
from search_area
where name = %s"""
cur.execute(sql_check, (citylist[0],))
if cur.fetchone() is not None:
logger.info("City already exists: " + citylist[0])
return
sql_search_area = """insert
into search_area (name)
values (%s)"""
cur.execute(sql_search_area, (citylist[0],))
# city_id = cur.lastrowid
sql_identity = """select
currval('search_area_search_area_id_seq')
"""
cur.execute(sql_identity, ())
search_area_id = cur.fetchone()[0]
sql_city = """insert
into city (name, search_area_id)
values (%s,%s)"""
cur.execute(sql_city, (city, search_area_id,))
logger.info("Added city " + city)
logger.debug(str(len(neighborhoods)) + " neighborhoods")
if len(neighborhoods) > 0:
sql_neighborhood = """
insert into neighborhood(name, search_area_id)
values(%s, %s)
"""
for neighborhood in neighborhoods:
cur.execute(sql_neighborhood, (neighborhood,
search_area_id,))
logger.info("Added neighborhood " + neighborhood)
else:
logger.info("No neighborhoods found for " + city)
conn.commit()
except UnicodeEncodeError:
# if sys.version_info >= (3,):
# logger.info(s.encode('utf8').decode(sys.stdout.encoding))
# else:
# logger.info(s.encode('utf8'))
# unhandled at the moment
pass
except Exception:
logger.error("Error collecting city and neighborhood information")
raise
except Exception:
logger.error("Error getting city info from website")
raise
def display_room(config, room_id):
webbrowser.open(config.URL_ROOM_ROOT + str(room_id))
def display_host(config, host_id):
webbrowser.open(config.URL_HOST_ROOT + str(host_id))
def fill_loop_by_room(config, survey_id):
"""
Master routine for looping over rooms (after a search)
to fill in the properties.
"""
room_count = 0
while room_count < config.FILL_MAX_ROOM_COUNT:
try:
if len(config.HTTP_PROXY_LIST) == 0:
logger.info(
"No proxies left: re-initialize after {0} seconds".format(
config.RE_INIT_SLEEP_TIME))
time.sleep(config.RE_INIT_SLEEP_TIME) # be nice
config = ABConfig()
room_count += 1
listing = db_get_room_to_fill(config, survey_id)
if listing is None:
return None
else:
if listing.ws_get_room_info(config.FLAGS_ADD):
pass
else: # Airbnb now seems to return nothing if a room has gone
listing.save_as_deleted()
except AttributeError:
logger.error("Attribute error: marking room as deleted.")
listing.save_as_deleted()
except Exception as e:
logger.error("Error in fill_loop_by_room:" + str(type(e)))
raise
def parse_args():
"""
Read and parse command-line arguments
"""
parser = argparse.ArgumentParser(
description='Manage a database of Airbnb listings.',
usage='%(prog)s [options]')
parser.add_argument("-v", "--verbose",
action="store_true", default=False,
help="""write verbose (debug) output to the log file""")
parser.add_argument("-c", "--config_file",
metavar="config_file", action="store", default=None,
help="""explicitly set configuration file, instead of
using the default <username>.config""")
# Only one argument!
group = parser.add_mutually_exclusive_group()
group.add_argument('-asa', '--addsearcharea',
metavar='search_area', action='store', default=False,
help="""get and save the name and neighborhoods
for search area (city)""")
group.add_argument('-asv', '--addsurvey',
metavar='search_area', type=str,
help="""add a survey entry to the database,
for search_area""")
group.add_argument('-dbp', '--dbping',
action='store_true', default=False,
help='Test the database connection')
group.add_argument('-dh', '--displayhost',
metavar='host_id', type=int,
help='display web page for host_id in browser')
group.add_argument('-dr', '--displayroom',
metavar='room_id', type=int,
help='display web page for room_id in browser')
group.add_argument('-f', '--fill', nargs='?',
metavar='survey_id', type=int, const=0,
help='fill details for rooms collected with -s')
group.add_argument('-lsa', '--listsearcharea',
metavar='search_area', type=str,
help="""list information about this search area
from the database""")
group.add_argument('-lr', '--listroom',
metavar='room_id', type=int,
help='list information about room_id from the database')
group.add_argument('-ls', '--listsurveys',
action='store_true', default=False,
help='list the surveys in the database')
group.add_argument('-psa', '--printsearcharea',
metavar='search_area', action='store', default=False,
help="""print the name and neighborhoods for
search area (city) from the Airbnb web site""")
group.add_argument('-pr', '--printroom',
metavar='room_id', type=int,
help="""print room_id information
from the Airbnb web site""")
group.add_argument('-ps', '--printsearch',
metavar='survey_id', type=int,
help="""print first page of search information
for survey from the Airbnb web site""")
group.add_argument('-psn', '--printsearch_by_neighborhood',
metavar='survey_id', type=int,
help="""print first page of search information
for survey from the Airbnb web site,
by neighborhood""")
group.add_argument('-psz', '--printsearch_by_zipcode',
metavar='survey_id', type=int,
help="""print first page of search information
for survey from the Airbnb web site,
by zipcode""")
group.add_argument('-psb', '--printsearch_by_bounding_box',
metavar='survey_id', type=int,
help="""print first page of search information
for survey from the Airbnb web site,
by bounding_box""")
group.add_argument('-s', '--search',
metavar='survey_id', type=int,
help='search for rooms using survey survey_id')
group.add_argument('-sn', '--search_by_neighborhood',
metavar='survey_id', type=int,
help='search for rooms using survey survey_id')
group.add_argument('-sb', '--search_by_bounding_box',
metavar='survey_id', type=int,
help="""search for rooms using survey survey_id,
by bounding box
""")
group.add_argument('-sz', '--search_by_zipcode',
metavar='survey_id', type=int,
help="""search for rooms using survey_id,
by zipcode""")
group.add_argument('-V', '--version',
action='version',
version='%(prog)s, version ' +
str(SCRIPT_VERSION_NUMBER))
group.add_argument('-?', action='help')
args = parser.parse_args()
return (parser, args)
def main():
(parser, args) = parse_args()
logging.basicConfig(format='%(levelname)-8s%(message)s')
ab_config = ABConfig(args)
try:
if args.search:
survey = ABSurveyByNeighborhood(ab_config, args.search)
survey.search(ab_config.FLAGS_ADD)
elif args.search_by_neighborhood:
survey = ABSurveyByNeighborhood(ab_config, args.search_by_neighborhood)
survey.search(ab_config.FLAGS_ADD)
elif args.search_by_zipcode:
survey = ABSurveyByZipcode(ab_config, args.search_by_zipcode)
survey.search(ab_config.FLAGS_ADD)
elif args.search_by_bounding_box:
survey = ABSurveyByBoundingBox(ab_config, args.search_by_bounding_box)
survey.search(ab_config.FLAGS_ADD)
elif args.fill is not None:
fill_loop_by_room(ab_config, args.fill)
elif args.addsearcharea:
ws_get_city_info(ab_config, args.addsearcharea, ab_config.FLAGS_ADD)
elif args.addsurvey:
db_add_survey(ab_config, args.addsurvey)
elif args.dbping:
db_ping(ab_config)
elif args.displayhost:
display_host(ab_config, args.displayhost)
elif args.displayroom:
display_room(ab_config, args.displayroom)
elif args.listsearcharea:
list_search_area_info(ab_config, args.listsearcharea)
elif args.listroom:
listing = ABListing(ab_config, args.listroom, None)
listing.print_from_db()
elif args.listsurveys:
list_surveys(ab_config)
elif args.printsearcharea:
ws_get_city_info(ab_config, args.printsearcharea, ab_config.FLAGS_PRINT)
elif args.printroom:
listing = ABListing(ab_config, args.printroom, None)
listing.ws_get_room_info(ab_config.FLAGS_PRINT)
elif args.printsearch:
survey = ABSurveyByNeighborhood(ab_config, args.printsearch)
survey.search(ab_config.FLAGS_PRINT)
elif args.printsearch_by_neighborhood:
survey = ABSurveyByNeighborhood(ab_config, args.printsearch_by_neighborhood)
survey.search(ab_config.FLAGS_PRINT)
elif args.printsearch_by_bounding_box:
survey = ABSurveyByBoundingBox(ab_config, args.printsearch_by_bounding_box)
survey.search(ab_config.FLAGS_PRINT)
elif args.printsearch_by_zipcode:
survey = ABSurveyByZipcode(ab_config, args.printsearch_by_zipcode)
survey.search(ab_config.FLAGS_PRINT)
else:
parser.print_help()
except (SystemExit, KeyboardInterrupt):
sys.exit()
except Exception:
logger.exception("Top level exception handler: quitting.")
sys.exit(0)
if __name__ == "__main__":
main()