index.py 17 KB

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