index.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. #!/usr/bin/python3
  2. import mysql.connector
  3. import requests
  4. from bs4 import BeautifulSoup
  5. import urllib.parse
  6. # import re
  7. # from sys import exit as exit
  8. # import json
  9. import datetime
  10. import custom_email
  11. from tabulate import tabulate
  12. from configparser import ConfigParser
  13. from os import path
  14. import logging
  15. ### TO DO ###
  16. #
  17. # Print useful reports (land only, house and land, etc)
  18. # Check if db entries no longer appear online (mark expired)
  19. # When checking online from various sites, check if address already exists in db
  20. # - if so, warn user and do not add
  21. # Add date_added to initial entries
  22. # Check results against database for changes
  23. # - update and add/change date_modified
  24. # Add argument to run update query when results.py is calles
  25. # Add database column to hold parcel number. Make links to GIS servers
  26. #
  27. # IDENTIFY NEW PROPERTIES!!
  28. #
  29. # Automate db opening and closing when calling dbinsert()
  30. #
  31. #############
  32. class Property:
  33. """Description of a proerty"""
  34. def __init__(self, site_name, type, MLS, address, city, st, zip, county, price, acres, title='', sqft=0, bedrooms=0,
  35. baths=0, description='', link=''):
  36. self.site_name = site_name
  37. self.type = type
  38. self.MLS = MLS
  39. self.title = title
  40. self.sqft = sqft
  41. self.bedrooms = bedrooms
  42. self.baths = baths
  43. self.address = address
  44. self.city = city
  45. self.st = st
  46. self.zip = zip
  47. self.county = county
  48. self.price = price
  49. self.acres = acres
  50. self.description = description
  51. self.link = link
  52. class Parameters:
  53. '''Parameters taken from config file'''
  54. def __init__(self, file='landsearch.conf'):
  55. self.file = file
  56. if not path.exists(self.file):
  57. raise FileNotFoundError("The config file cannot be opened", self.file)
  58. try:
  59. self.config = ConfigParser()
  60. self.config.read(self.file)
  61. self.search_params = self.config['Search']
  62. self.log_params = self.config['Logging']
  63. except Exception as err:
  64. print(err, "Using default search Parameters")
  65. class Mylogger:
  66. ''' Logging tool for this session'''
  67. def __init__(self):
  68. log_params = Parameters().log_params
  69. filename=log_params.get('log_file')
  70. level=int(log_params.get('logging_level', str('30')))
  71. format='%(asctime)s %(levelname)-8s %(message)s'
  72. datefmt='%Y-%m-%d %H:%M:%S'
  73. class Search:
  74. '''Universal Search Criteria'''
  75. def checktype(self, attribute):
  76. '''Fixes string None in config file and converts to '' '''
  77. if not attribute == 'None':
  78. return attribute
  79. else:
  80. return ''
  81. def __init__(self, file='landsearch.conf'):
  82. # self.file = file
  83. # if not path.exists(self.file):
  84. # raise FileNotFoundError("The config file cannot be opened", self.file)
  85. # try:
  86. # config = ConfigParser()
  87. # config.read(self.file)
  88. # search_params = config['Search']
  89. # log_params = config['Logging']
  90. # except FileNotFoundError as err:
  91. # print(err, "Using default search parameters.")
  92. # except Exception as err:
  93. # print(err, "Using default search parameters.")
  94. params = Parameters()
  95. search_params = params.search_params
  96. log_params = params.log_params
  97. logging.basicConfig(filename=log_params.get('log_file'),
  98. level=int(log_params.get('logging_level', str('30'))),
  99. format='%(asctime)s %(levelname)-8s %(message)s',
  100. datefmt='%Y-%m-%d %H:%M:%S') ## Default log level WARNING (30)
  101. logging.getLogger("urllib3").setLevel(logging.WARNING) ## Supress Requests method logging
  102. logging.debug("Log level set to %s", logging.root.level)
  103. Mylogger()
  104. county = search_params.get('county', ['Gwinnett', 'Hall', 'Jackson', 'Walton', 'Barrow'])
  105. if isinstance(county, str):
  106. county = county.split(", ")
  107. type = search_params.get('type', ['farm', 'house', 'land'])
  108. if isinstance(type, str):
  109. type = type.split(", ")
  110. self.types = ['land', 'farm', 'home', 'house']
  111. self.county = county
  112. self.lower_price = self.checktype(search_params.get('lower_price', '0'))
  113. self.upper_price = self.checktype(search_params.get('upper_price', '525000'))
  114. self.lower_acres = self.checktype(search_params.get('lower_acres', '5'))
  115. self.upper_acres = self.checktype(search_params.get('upper_acres', '15'))
  116. self.type = type ##accept list!
  117. self.lower_sqft = self.checktype(search_params.get('lower_sqft', ''))
  118. self.upper_sqft = self.checktype(search_params.get('upper_sqft', ''))
  119. self.lower_bedrooms = self.checktype(search_params.get('lower_bedrooms', ''))
  120. self.upper_bedrooms = self.checktype(search_params.get('upper_bedrooms', ''))
  121. for property_type in self.type:
  122. assert property_type in self.types, (
  123. "Unknown type '" + property_type + "'. Property Type must be of type: " + str(self.types))
  124. ## FOR TESTING, PRINT ALL ATTRIBUTES OF SEARCH ##
  125. logging.debug(vars(self))
  126. class ImproperSearchError(Exception):
  127. def __init__(self, search, message="Improper Search. Must use instance of Search class"):
  128. self.search = search
  129. self.message = message
  130. super().__init__(self.message)
  131. class MLSDATA:
  132. """Fetches and stores MLS Data
  133. Currently only supports GeorgiaMLS.com (GMLS)"""
  134. counties = ['Gwinnett', 'Barrow', 'Hall', 'Jackson', 'Walton']
  135. GoogleAPIKey = 'AIzaSyAXAnpBtjv760W8YIPqKZ0dFXpwAaZN7Es'
  136. live_google = True
  137. def __init__(self, mlstype):
  138. self.parameters = Parameters()
  139. self.help = "This is a class that will retrieve MLS data from various sources, store the info in a database, and run queries on the data."
  140. self.mlstype = mlstype.lower() ## Determines what kind of data is to be retreieve (gmls, Zillow, etc)
  141. self.cursor = ''
  142. self.cnx = ''
  143. self.new_listings = []
  144. self.email = self.parameters.search_params.getboolean('email')
  145. print('Email ' + str(self.email))
  146. def stringbuilder(self, search: Search, county):
  147. """ Takes Search class and build appropriate URL query based on mlstype. Currently only supports gmls."""
  148. if self.mlstype == 'gmls':
  149. base_addr = 'https://www.georgiamls.com/real-estate/search-action.cfm?'
  150. params = [('cnty', county),
  151. ('lpl', search.lower_price), ('lph', search.upper_price),
  152. ('acresL', search.lower_acres), ('acresH', search.upper_acres),
  153. ('sqftl', search.lower_sqft), ('sqfth', search.upper_sqft),
  154. ('orderBy', 'b'),
  155. ('scat', '1'),
  156. ('sdsp', 'g')]
  157. for type in search.type:
  158. if 'land' in type.lower():
  159. params.append(('typ', 'll'))
  160. if 'farm' in type.lower():
  161. params.append(('typ', 'af'))
  162. if 'home' in type.lower():
  163. params.append(('typ', 'sd'))
  164. if 'house' in type.lower():
  165. params.append(('typ', 'sd'))
  166. search_string = base_addr + urllib.parse.urlencode(params)
  167. print(search_string)
  168. logging.debug(search_string)
  169. return search_string
  170. def break_address(self, address):
  171. """Takes an address string in the form 'street address|city, state zip' and returns a list"""
  172. street = address[:address.find('|')]
  173. csz = address[address.find('|') + 1:]
  174. city = csz[:csz.find(',')]
  175. st = csz[csz.find(',') + 1:].split(' ')[1]
  176. zip = csz[csz.find(',') + 1:].split(' ')[2]
  177. split_address = [street, city, st, zip]
  178. return split_address
  179. def gmlsparser(self, URL, county, pages=''):
  180. """ Retrieve the website for georgiamls.com and returns a list of Property objects.
  181. UNIQUE TO GEORGIAMLS.COM ONLY!!"""
  182. properties_list = []
  183. r = requests.get(URL)
  184. soup = BeautifulSoup(r.content, 'html5lib')
  185. if pages == '':
  186. try:
  187. pages = soup.find("div", {'class': 'small listing-pagination-count'}).getText().strip().split(" ")[-1]
  188. current_page = \
  189. soup.find("div", {'class': 'small listing-pagination-count'}).getText().strip().split(" ")[-3]
  190. except AttributeError as err:
  191. print("No Results Found.")
  192. return
  193. else:
  194. print('pages already set to: ' + str(pages))
  195. for page in range(0, int(pages)):
  196. print('Processing Page: ' + str(page + 1) + ' of ' + str(pages))
  197. if not page == 0:
  198. next_URL = URL + '&start=' + str(((12 * page) + 1))
  199. soup = BeautifulSoup(requests.get(next_URL).content, 'html5lib')
  200. raw_listings = soup.findAll("div", {'class': 'col-xs-12 col-sm-6 col-lg-4 text-center listing-gallery'})
  201. for listing in raw_listings:
  202. items = listing.findAll("p") ##
  203. site_name = self.mlstype
  204. MLS = " ".join(items[3].getText().strip()[6:15].split()) ## MLS NUMBER
  205. title = '' ## Listing Title (address if no title)
  206. price = items[0].string.strip() ## Price
  207. if self.mlstype == 'gmls':
  208. link = 'https://www.georgiamls.com' + listing.a['href']
  209. detail_request = requests.get(link)
  210. detail_soup = BeautifulSoup(detail_request.content, 'html5lib')
  211. details = detail_soup.findAll('tr')
  212. bedbath = details[1].findAll('td')[1].getText().strip().split('/')
  213. br = bedbath[0][:-3]
  214. ba = bedbath[1][:-3]
  215. baths = ba ## IF House is present
  216. bedrooms = br ## IF House is present
  217. address = ''
  218. for element in details:
  219. if 'sqft' in element.getText():
  220. sqft = element.findAll('td')[1].getText().strip()[:-5].replace(',', '')
  221. if 'lot size' in element.getText().lower():
  222. acres = element.findAll('td')[1].getText().strip()[:-6]
  223. if 'Property Type' in element.getText():
  224. ptype = element.findAll('td')[1].getText().strip()
  225. if 'acreage' in ptype.lower():
  226. type = 'af'
  227. elif 'land lot' in ptype.lower():
  228. type = 'll'
  229. elif 'single family home' in ptype.lower():
  230. type = 'sf'
  231. else:
  232. type = 'unknown'
  233. if 'Address' in element.getText():
  234. if not address: # Prevents finding the word 'address' elsewhere in the listings
  235. address = element.findAll('td')[1]
  236. # 7 print("TEST ADDRESS: ", element)
  237. street_address = list(address)[0].strip()
  238. csz = list(address)[2].strip()
  239. split_address = self.break_address(street_address + '|' + csz)
  240. description = detail_soup.find('div', {'id': 'listing-remarks'}).getText().strip().replace('\t', '')
  241. data = Property(site_name=self.mlstype,
  242. type=type,
  243. MLS=MLS,
  244. bedrooms=bedrooms,
  245. baths=baths,
  246. sqft=sqft,
  247. address=split_address[0],
  248. city=split_address[1].title(),
  249. st=split_address[2].upper(),
  250. zip=split_address[3],
  251. county=county.title(),
  252. price=price.replace('$', '').replace(',', ''),
  253. acres=acres,
  254. description=description,
  255. link=link)
  256. properties_list.append(data)
  257. logging.debug('Scanned: ' + data.address)
  258. print('Scanned: ' + data.address)
  259. return properties_list
  260. def getmlsdata(self, search: Search, county):
  261. """This is the main entrypoint. Takes arguments to pass to stringbuilder to create the URL.
  262. Selects appropriate parser based on self.mlstype from class intance.
  263. Needs any modifications from the standard search ($0 to $500,000, 5 to 15 acres, etc)
  264. See class search for more information.
  265. --> 9/1/20 - takes Search class as argument. All properties are handled by the class <--"""
  266. logging.info('getgmlsdata starting.')
  267. logging.debug('Scanning: ' + county + " county")
  268. if isinstance(search, Search):
  269. if not county in self.counties: ### FIX for lower()
  270. print("County " + county + " not regognized. Exiting")
  271. else:
  272. print("Scanning for results in " + county + " using the " + self.mlstype.upper() + " database.")
  273. if self.mlstype == 'gmls':
  274. list = self.gmlsparser(self.stringbuilder(search, county), county)
  275. logging.info("Completed search in " + county + " county. " + str(len(list)) + " total properties scanned.")
  276. return list
  277. else:
  278. raise ImproperSearchError(search)
  279. def checkdb(self, criteria_dict):
  280. """Check dictionary of critera against database.
  281. Currently accepts keys: MLS, title, address (street number/name, not city/state/zip).
  282. Returns True if records exists."""
  283. if self.cursor: ## Check if DB is connected
  284. for criteria in criteria_dict:
  285. ## Determine criteria passed, and execute queries for each
  286. if criteria == 'MLS':
  287. self.cursor.execute("SELECT COUNT(*) FROM properties WHERE MLS = %(MLS)s GROUP BY id",
  288. {criteria: criteria_dict[criteria]})
  289. if self.cursor.rowcount > 0: return self.cursor.rowcount # stop for loop if match already found.
  290. elif criteria == 'title':
  291. self.cursor.execute("SELECT COUNT(*) FROM properties WHERE title = %(title)s GROUP BY id",
  292. {criteria: criteria_dict[criteria]})
  293. if self.cursor.rowcount > 0: return self.cursor.rowcount # stop for loop if match already found.
  294. elif criteria == 'address':
  295. self.cursor.execute("SELECT COUNT(*) FROM properties WHERE address = %(address)s GROUP BY id",
  296. {criteria: criteria_dict[criteria]})
  297. if self.cursor.rowcount > 0: return self.cursor.rowcount # stop for loop if match already found.
  298. else:
  299. print("Cannot search on parameter: " + criteria)
  300. return self.cursor.rowcount
  301. else:
  302. print("Database is not connected or cursor not filled. Use function 'connectdb()' to establish")
  303. def getGoogle(self, property):
  304. """Supplies date from Google Distance Matrix API to populate
  305. distance_to_work
  306. time_to_work
  307. distance_to_school
  308. time_to_school
  309. Costs money, so it should only be called when inserting a new db record.
  310. Returns distance in METERS (1m = 0.000621371 mi) and time in SECONDS
  311. returns fully populated Propery object."""
  312. print("Fetching live Google Data. $$")
  313. logging.warning("Calling Google API. $$")
  314. destination1 = 'Hebron Christian Acadamy' ## Working query for Hebron Christian Acadamy
  315. destination2 = 'JHRJ+FJ Atlanta, Georgia' ## Plus code for Hourly parking at Int'l Terminal, KATL
  316. params = {}
  317. params['units'] = 'imperial'
  318. params['origins'] = property.address + ', ' + property.city + ' ' + property.st
  319. params['destinations'] = 'Hebron Christian Acadamy|JHRJ+FJ Atlanta, Georgia'
  320. params['key'] = self.GoogleAPIKey
  321. baseURL = 'https://maps.googleapis.com/maps/api/distancematrix/json?'
  322. API_URL = baseURL + urllib.parse.urlencode(params)
  323. # print(API_URL)
  324. # Send Request and capture result as json
  325. try:
  326. google_result = requests.get(API_URL).json()
  327. if google_result['status'] == 'OK':
  328. property.distance_to_school = google_result['rows'][0]['elements'][0]['distance']['value']
  329. property.time_to_school = google_result['rows'][0]['elements'][0]['duration']['value']
  330. property.distance_to_work = google_result['rows'][0]['elements'][1]['distance']['value']
  331. property.time_to_work = google_result['rows'][0]['elements'][1]['duration']['value']
  332. except:
  333. print("ERROR: Failed to obtain Google API data")
  334. def insertrecord(self, property, work_address=None, school_address=None):
  335. """Inserts record into database. Takes argument Property class object."""
  336. if self.cursor:
  337. criteria_dict = property.__dict__
  338. criteria_dict['Date_Added'] = str(datetime.date.today())
  339. placeholder_columns = ", ".join(criteria_dict.keys())
  340. placeholder_values = ", ".join([":{0}".format(col) for col in criteria_dict.keys()])
  341. qry = "INSERT INTO properties ({placeholder_columns}) VALUES {placeholder_values}".format(
  342. placeholder_columns=placeholder_columns, placeholder_values=tuple(criteria_dict.values()))
  343. try:
  344. self.cursor.execute(qry)
  345. self.cnx.commit()
  346. print("Inserted " + criteria_dict['MLS'] + " | " + criteria_dict['address'] + " into database.")
  347. logging.debug("Inserted " + criteria_dict['MLS'] + " | " + criteria_dict['address'] + " into database.")
  348. except Exception as e:
  349. print("Could not insert " + criteria_dict['address'] + " into database. Database connection error.")
  350. logging.warning("Could not insert " + criteria_dict['address'] + "into database. Database connection "
  351. "error.")
  352. logging.warning(str(e))
  353. else:
  354. print("Database is not connected or cursor not filled. Use function 'connectdb()' to establish")
  355. def connectdb(self, host='192.168.100.26', user='landsearchuser', password='1234', database='landsearch'):
  356. """Connects to database and returns a cursor object"""
  357. self.cnx = mysql.connector.connect(host=host, user=user, password=password, database=database, buffered=True)
  358. self.cursor = self.cnx.cursor()
  359. return self.cursor
  360. def closedb(self):
  361. """Cleanly close the db."""
  362. self.cursor.close()
  363. self.cnx.close()
  364. def dbinsert(self, properties: list):
  365. """Inserts records into database. Takes list of Property class objects"""
  366. if not properties == None:
  367. if not isinstance(properties, list):
  368. raise TypeError('type list required')
  369. for property in properties:
  370. if not self.checkdb({'MLS': property.MLS, 'address': property.address}):
  371. if self.live_google: self.getGoogle(
  372. property) ## <- This will populate distance and time fields if set TRUE
  373. self.insertrecord(property)
  374. self.new_listings.append(property)
  375. else:
  376. print(property.MLS + ' | ' + property.address + ' is already in db. Not inserted.')
  377. ##REMOVE FOR TESTING###
  378. # self.new_listings.append(property)
  379. #######################
  380. else:
  381. print("Empty dataset. No records to insert.")
  382. logging.info("Database Update Complete.")
  383. logging.info(str(len(self.new_listings)) + " new listings found.")
  384. def alerts(self):
  385. pass
  386. def email_results(self):
  387. global mymail
  388. sendto = ['stagl.mike@gmail.com', 'M_Stagl@hotmail.com']
  389. if self.email:
  390. ''' Send some kind of email! '''
  391. # If there are new listings, populate email ##
  392. if len(self.new_listings) > 0:
  393. logging.debug("email_results" + str(self.email))
  394. body = ''
  395. data = []
  396. subj = "New Real Estate Listings for " + str(datetime.date.today())
  397. for listing in self.new_listings:
  398. row = []
  399. body += listing.MLS + " | " + listing.address + " | " + listing.acres + " | " + listing.price + " | " + listing.link + "\n"
  400. row.append(listing.MLS)
  401. row.append(listing.address)
  402. row.append('{:0,.2f}'.format(float(listing.acres)))
  403. row.append(listing.sqft)
  404. row.append('${:0,.0f}'.format(int(listing.price)))
  405. row.append(listing.time_to_school / 60 if hasattr(listing, 'time_to_school') else 'NA')
  406. row.append(listing.link)
  407. data.append(row)
  408. body = """\
  409. Daily Real Estate Search Report\n
  410. The following properties have been found which may be of interest.\n
  411. """
  412. results = tabulate(data,
  413. headers=['MLS', 'Address', 'Acres', 'sqft', 'Price', 'Time to School', 'link'])
  414. body += results
  415. mymail = custom_email.simplemail(subj, body, sendto)
  416. else:
  417. body = 'No new listings found'
  418. subj = '0 New Real Estate Listings for ' + str(datetime.date.today())
  419. try:
  420. mymail = custom_email.simplemail(subj, body, sendto)
  421. mymail.sendmail()
  422. print("Email sent.")
  423. logging.info('Emails sent to: ' + str(sendto))
  424. except Exception as e:
  425. print("Error sending email. " + str(e))
  426. logging.warning("Error sending email. " + str(e))
  427. else:
  428. print("Suppressing email based on landsearch.conf preferences.")
  429. logging.warning("Suppressing email based on landsearch.conf preferences.")
  430. if __name__ == '__main__':
  431. gmls = MLSDATA('GMLS') # Create MLSDATA object
  432. mysearch = Search() # Create a custom search object
  433. myresults = []
  434. ## Create function in MLSDATA module:
  435. # - takes counties from configparser and calls getmlsdata for each county.
  436. # - Compiles results into single list and returns that list
  437. # - User code would look something like this:
  438. # _ mysearch = Search()
  439. # _ mydata = gmls.findalllistings(mysearch) # This would control the looping of counties and return a list like normal
  440. # _ gmls.dbinsert(myresults) # This would automate db opening and closing
  441. for county in mysearch.county:
  442. print("local search: ", county)
  443. mysearch = Search() ## Search used to take county as parameter, so this loop would work. Now Search class contains list. loop must occur in getmlsdata module
  444. mydata = gmls.getmlsdata(mysearch, county)
  445. if mydata: # Avoids a crash is there is no data
  446. for listing in mydata:
  447. myresults.append(listing)
  448. # print(len(myresults))
  449. # print(myresults[0].address)
  450. gmls.connectdb()
  451. gmls.dbinsert(myresults)
  452. gmls.closedb()
  453. gmls.email_results()