index.py 24 KB

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