index.py 19 KB

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