#!/usr/bin/python2.7 # Author - Neil Jones - neiljsecurity.co.uk Version 0.2 import BeautifulSoup,smtplib import sys,re,urllib2,sqlite3 from email.MIMEText import MIMEText from email.mime.multipart import MIMEMultipart class watcher: useragent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2.10) Gecko/20100914 Firefox/3.6.10 ( .NET CLR 3.5.30729; .NET4.0E" email = True #Email Settings emailUsr = "" #email user emailPass = "" #email password emailTo = ["blah@gmail.com"] #Email End def __init__(self): self.loadDB() def seturl(self,url): self.url = url def loadDB(self): self.data = {} self.db = sqlite3.connect("cars.sqlite") if self.db.execute("select count(*) from sqlite_master").fetchone()[0] == 0: self.db.execute("""CREATE TABLE cars (id varchar(60) primary key, title varchar(300), year varchar(4), bodystyle varchar(10), mileage varchar(20), transmission varchar(20), engine varchar(20), fuel varchar(20), price varchar(10), description varchar(2000), image varchar(300) );""") self.db.commit() def hasCar(self,id): if self.db.execute("select count(id) from cars WHERE id = ?",[id]).fetchone()[0] == 0: return False else: return True def addCar(self,id): self.db.execute("INSERT INTO cars (engine, mileage, description,title, transmission, image, price, bodystyle, year, fuel, id) VALUES (?,?,?,?,?,?,?,?,?,?,?)",self.data[id].values()) self.db.commit() pass def getCarDetails(self,id): try: req = urllib2.Request('http://www.autotrader.co.uk/classified/advert/' + id.split('advert')[1]) req.add_header('User-Agent',self.useragent) response = urllib2.urlopen(req) thepage = response.read() soup = BeautifulSoup.BeautifulSoup(thepage) if soup.find('div',{'class':'fullpagesorryholder'},recursive=True) != None: print "yay" return desc = soup.find('div',{'class' : 'vehicleDescription'}) details = desc.find('ul',{'id' : 'mainVehicleAttributes'}).findAll('span') self.data[id] = {} self.data[id][u'description'] = desc.find('span',{'id': 'leadDescription'}).text + " " self.data[id][u'description'] = self.data[id][u'description'] + desc.find('span',{'id': 'remainingDescription'}).text self.data[id][u'id'] = unicode(id) self.data[id][u'image'] = soup.find('img',{'class' : re.compile('masterImage')})["src"] for detail in details: if detail["class"] == "reg notAvailable": continue self.data[id][detail["class"]] = detail.text self.data[id][u'title'] = soup.find('h1',{'id':'fullPageMainTitle'}).text self.data[id][u'price'] = soup.find('div',{'id':'price'}).text[1:] self.addCar(id) except: print "Fatal Error: Could not download page ", sys.exc_info() sys.exit(-1) def watch(self): try: next = True while next == True: req = urllib2.Request(self.url) req.add_header('User-Agent',self.useragent) response = urllib2.urlopen(req) thepage = response.read() soup = BeautifulSoup.BeautifulSoup(thepage) self.parse(soup) nextPage = soup.find('div',{'class': 'paginator top'}).find('a',{'class':'button next'}) if nextPage != None: try: nextPage = nextPage["href"] self.url = nextPage except: next = False else: next = False if self.email == True and len(self.data) > 0: self.sendEmail() except: print "Fatal Error: Could not download page ", sys.exc_info() sys.exit(-1) def parse(self,souppage): results = souppage.find('div',{'class':'resultsWrapper '}) if results == None: print "Fatal Error: Could not find search results" sys.exit(-1) results = results.findAll('div',{'class':re.compile(' searchResult ')},recursive=True) for result in results: title = result.find('a',{'class' : 'external title'}) print title["title"] try: id = result["id"] print id if id != None: print "Has Car? ", self.hasCar(id) if self.hasCar(id) == False: #add the car to database self.getCarDetails(id) except SystemExit: sys.exit(-1) except: print "Error parsing page" def sendEmail(self): for person in self.emailTo: msg = MIMEMultipart('alternative') msg['Subject'] = "New Cars from AutoTrader" msg['From'] = self.emailUsr msg['To'] = person htmlMsg = """\

New Cars


""" for car in self.data: htmlMsg += "" htmlMsg += "" htmlMsg += "" htmlMsg += "" htmlMsg += "" htmlMsg += "" htmlMsg += "" htmlMsg += "" htmlMsg += "" htmlMsg += "" try: htmlMsg += "" except: print str(self.data[car]["description"].encode("latin-1")), sys.exc_info() htmlMsg += "" htmlMsg += """\
Title Engine Mileage Transmission BodyStyle Fuel Year Mileage Price
" + self.data[car]["title"].encode("ascii",errors='ignore') + "" + self.data[car]["engine"].encode("ascii",errors='ignore') + "" + self.data[car]["mileage"].encode("ascii",errors='ignore') + "" + self.data[car]["transmission"].encode("ascii",errors='ignore') + "" + self.data[car]["bodystyle"].encode("ascii",errors='ignore') + "" + self.data[car]["fuel"].encode("ascii",errors='ignore') + "" + self.data[car]["year"].encode("ascii",errors='ignore') + "" + self.data[car]["mileage"].encode("ascii",errors='ignore') + "" + self.data[car]["price"].encode("ascii",errors='ignore') + "
Description: %s" % self.data[car]["description"].encode("ascii",errors='ignore') htmlMsg += " More
""" part1 = MIMEText("New Cars %s " % str(self.data),'plain') part2 = MIMEText(htmlMsg,'html') msg.attach(part1) msg.attach(part2) server = smtplib.SMTP('smtp.gmail.com:587') server.ehlo() server.starttls() server.ehlo() server.login(self.emailUsr,self.emailPass) server.sendmail(self.emailUsr, person, msg.as_string()) server.quit() def cleanup(self): self.db.close() if __name__ == "__main__": autotrader = watcher(); autotrader.seturl("") # example : http://www.autotrader.co.uk/search/used/cars/abarth/punto_evo/postcode/cf244sh/radius/1500/quicksearch/true autotrader.watch() autotrader.cleanup()