def search_and_collect_listings(date_1, date_2): api = airbnb.Api() search = api.get_homes(location, checkin=date_1, checkout=date_2, items_per_grid=100) list_of_listings = [] ##This will find the listings section and assign raw_listings to the array. for x in search['explore_tabs'][0]['sections']: if x['result_type'] == 'listings': raw_listings = x['listings'] for x in raw_listings: list_of_listings.append(x) print("Found ", len(raw_listings), " listings!") return list_of_listings
def get_listings(bot, job): print('started scan new listing') list_of_subs = get_all_subs() for sub in list_of_subs: items_offset = 0 actual_listings = set() has_next_page = True api = airbnb.Api(randomize=True, currency=sub[0]) while has_next_page: homes = api.get_homes(query=sub[1], adults=sub[2], price_max=sub[3], checkin=sub[4][:10], checkout=sub[5][:10], room_types=sub[6], offset=items_offset) # Отступ объявлений try: try: listings = homes['explore_tabs'][0]["sections"][1]['listings'] except KeyError: logging.info( f'Have a KeyError on {sub[7]} subscription while trying to get new listings') except IndexError: try: listings = homes['explore_tabs'][0]["sections"][0]['listings'] except KeyError: logging.info( f'Have a KeyError on {sub[7]} subscription while trying to get new listings') for listing in listings: actual_listings.add(listing["listing"]["id"]) has_next_page = homes['explore_tabs'][0]['pagination_metadata']['has_next_page'] try: items_offset = homes['explore_tabs'][0]['pagination_metadata']['items_offset'] except KeyError: print('no next page while scanning for new listings') print('actual', actual_listings) print(len(actual_listings)) new_listings = find_new_listings(actual_listings, sub[7]) send_notification(new_listings, sub, bot)
def send_notification(new_listings, parameters, bot): for listing_id in new_listings: url = f'https://www.airbnb.com/rooms/{listing_id}?guests={parameters[2]}&' \ f'adults={parameters[2]}&check_in={parameters[4][:10]}&check_out={parameters[5][:10]}' api = airbnb.Api(randomize=True, currency=parameters[0]) details = api.get_listing_details(listing_id) text = 'Hello, we have found new home for you:' \ f'' picture = details["pdp_listing_detail"]["photos"][0]["large"] keyboard = [[InlineKeyboardButton( 'See listing', callback_data='url', url=f'{url}')]] reply_markup = InlineKeyboardMarkup(keyboard) bot.send_photo( chat_id=parameters[8], photo=picture, caption=text, reply_markup=reply_markup) new_listing = ListingId(listing_id=listing_id, subscription=parameters[7]) session.add(new_listing) session.commit()
import airbnb import airbnb_secrets import csv items = 1 output_filename = "airbnb_chapelhill.csv" # Set CSV Header & line format csv_header = [ 'City', 'Latitude', 'Longitude', 'Type', 'Bathrooms', 'Bedrooms', 'Public Address', 'Localized City', 'Source' ] api = airbnb.Api() # api = airbnb.Api(airbnb_secrets.login, airbnb_secrets.password) api = airbnb.Api(access_token=airbnb_secrets.access_token) try: output_file = open(output_filename, 'w') csvwriter = csv.writer(output_file, dialect='excel') except IOError: print("Output file creation failed") exit(1) csvwriter.writerow(csv_header) while True: try: response = api.get_homes("Chapel Hill, NC, USA", items_per_grid=10, offset=items) except Exception: print("Terminating on error")
#Module Name: Airbnb API Client for Python #Date of the code: 4/19/20 #Programer(s) Name: Janeen Yamak, Brittany Kraemer, Rojan Rijal #Brief description: This file is a client for the Airbnb api. A user shall input the city, state, and offset and it shall return a list of apartments located in the near area #Data Structure: A list of Dictionaries #Algorithm: Parsing through a json list import airbnb api = airbnb.Api(randomize=True) def findApt(city, state): apts = [] location = city + ", " + state #should return a json object of apartments in the given location data = api.get_homes(location, offset=1, items_per_grid=10) #parse through the json file and grab the data we need and insert that data into a dictionary for k in data['explore_tabs'][0]['sections'][0]['listings']: aptInfo = {} aptInfo['name'] = k['listing']['name'] aptInfo['id'] = k['listing']['id'] aptInfo['urls'] = k['listing']['picture_urls'] aptInfo['guests'] = k['listing']['guest_label'].split(' ')[0] aptInfo['homeType'] = k['listing']['bedroom_label'] aptInfo['numOfBaths'] = k['listing']['bathroom_label'].split(' ')[0] numBedRooms = k['listing']['bed_label'].split(' ')[0] aptInfo['numBedroom'] = k['listing']['bed_label'].split(' ')[0]
def search_home(bot, update, user_data): query = update.callback_query user_data['available_listings'] = [] items_offset = 0 has_next_page = True api = airbnb.Api(randomize=True, currency=user_data["currency"]) while has_next_page: homes = api.get_homes(query=user_data['city'], adults=user_data["adults"], price_max=user_data["max_price"], checkin=user_data["check_in"], checkout=user_data["check_out"], room_types=user_data["room_type"], offset=items_offset) # Отступ объявлений try: try: listings = homes['explore_tabs'][0]["sections"][1]['listings'] except KeyError: text = "Sorry we could't process your request, please try again" query.edit_message_text(text) return greet_user(bot, update, user_data) except IndexError: try: listings = homes['explore_tabs'][0]["sections"][0]['listings'] except KeyError: text = "Sorry we could't process your request, please try again" query.edit_message_text(text) return greet_user(bot, update, user_data) for listing in listings: user_data['available_listings'].append(listing["listing"]["id"]) has_next_page = homes['explore_tabs'][0]['pagination_metadata']['has_next_page'] try: items_offset = homes['explore_tabs'][0]['pagination_metadata']['items_offset'] except KeyError: print('no next page') if len(user_data['available_listings']) < 200: bd_write_subscription(query, user_data) text = thank_text else: text = f'We have found {len(user_data["available_listings"])} offers for your criteria, this is too much,' \ f'you can see these offers by pressing button bellow, but your subscription will not be added to our ' \ f'database. If you still want to add subscription and get new offers, please tighten your search, ' \ f'set lower price for example' params = { # Ссылка для выдачи на веб на существующие варианты 'query': user_data['city'], 'adults': user_data["adults"], 'children': '0', 'price_min': '0', 'price_max': user_data["max_price"], 'checkin': user_data["check_in"], 'checkout': user_data["check_out"], 'room_types[]': user_data["room_type"], 'refinement_paths[]': '/homes', 'display_currency': user_data["currency"] } give_url = requests.get(web_url, params=params) keyboard = [[InlineKeyboardButton( 'Go to Airbnb', callback_data='url', url=f'{give_url.url}')]] reply_markup = InlineKeyboardMarkup(keyboard) query.edit_message_text(text, reply_markup=reply_markup)
from flask import Flask, jsonify, request import airbnb from datetime import date ## Setup app = Flask(__name__) api = airbnb.Api() port = 5000 ## Route @app.route('/') def home(): return "This is airbnb querying microservice" @app.route('/airbnb') def search(): location = request.args.get('location', None) startdate = request.args.get('startdate', None) enddate = request.args.get('enddate', None) numlistings = 50 result = api.get_homes(location, items_per_grid=numlistings, checkin=startdate, checkout=enddate) return jsonify(result) ## Init if __name__ == '__main__':
def __init__(self): self.api = airbnb.Api(randomize=True)
import requests import traceback import airbnb from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from bs4 import BeautifulSoup if os.path.exists('airbnb_token.txt'): with open('airbnb_token.txt', 'r') as file: airbnb_token = file.readline() api = airbnb.Api(access_token=airbnb_token) else: if os.path.exists('airbnb_auth.json'): with open('airbnb_auth.json', 'r') as file: json_repr = file.readline() data = json.loads(json_repr) username_str = data['email'] user_id_str = data['user_id'] password_str = data['password'] else: august_email = input("Airbnb Email Address: ") august_phone = input("Airbnb User ID (e.g. 12345678): ") august_pass = input("Airbnb Password: ") api = airbnb.Api(username_str, password_str) bnbhostapi = { 'username': user_id_str, 'password': password_str,