index.py 19 KB

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