def sendMail(idProp, link, sender, mail, phone, message): headers = { 'cookie': '__cfduid=d85a12ca3b01cb89db8d37da7b062fbf51560358480; frankie=17; random_template_viewer=53; xtvrn=$535162$; accountData=eyJuYW1lIjoiIiwiZW1haWwiOiIiLCJzaG9ydG5hbWUiOiIiLCJhdmF0YXIiOiIiLCJhY2NTZXNzaW9uIjoiIiwgInVybCI6Imh0dHBzOi8vd3d3LnlhcG8uY2wiLCAic2VjdXJlX3VybCI6ICJodHRwczovL3d3dzIueWFwby5jbCIsICJzZXJ2aWNlX3VybCI6ICJodHRwczovL3d3dy55YXBvLmNsIiB9; __asc=46fd09de16b4c9cf15701c66490; __auc=46fd09de16b4c9cf15701c66490; fpid=73003325faf25d15d8f8dda5c504b83a; _fbp=fb.1.1560358482569.1052203466; cto_lwid=8d7fba48-2077-4140-8387-3dda520876a3; _pulse2data=9f86587b-5bcc-42e2-b8a0-d7aa56277a1b%2Cv%2C%2C1560359384089%2CeyJpc3N1ZWRBdCI6IjIwMTktMDYtMTJUMTY6NTQ6NDNaIiwiZW5jIjoiQTEyOENCQy1IUzI1NiIsImFsZyI6ImRpciIsImtpZCI6IjIifQ..HSzhcqDFZVHAq_gPG5Q28w.spXmRYiU3cvpQ9Mx1NlOcL8QKM6PVMos04xdumZDX4hZq8PN5BZjVu5cHSK30aKKueii1VANu0FSNVPP34qok-oFYRrp2PRdAMNCXggoegew21oyYO868c6F9k0AwF79Dxx2_Scf674H6ChmLKBIzTaHLUmug1MO_MTbnDlGioXePeUgvT3gxoOPHJwvR9LkStlfK-3OyToqkBQ5t0HqoA.djEcsBRJNq5EnbM4IzMeWg%2C%2C0%2Ctrue%2C%2CeyJraWQiOiIyIiwiYWxnIjoiSFMyNTYifQ..5AyjySwnUP3t9-9d-8kRXnDsEPZfGP5eLcyTJokEQsY; utag_main=v_id:016b4c9cf001009861fb80bf19580307800700700093c$_sn:1$_se:5$_ss:0$_st:1560360381839$ses_id:1560358481922%3Bexp-session$_pn:1%3Bexp-session', 'origin': 'https://www.yapo.cl', 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'es,en-US;q=0.9,en;q=0.8,it;q=0.7,gl;q=0.6', 'user-agent': agentCreator.generateAgent(), 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8', 'accept': 'application/json, text/javascript, /; q=0.01', 'referer': link, 'authority': 'www.yapo.cl', 'x-requested-with': 'XMLHttpRequest', } data = { 'id': idProp, 'name': sender, 'email': mail, 'phone': phone, 'adreply_body': message } response = requests.post('https://www.yapo.cl/send_ar', headers=headers, data=data) #checkClient(idProp) return response
def scrap(d, h, operacion, tipo, region, lista, faillista): link = "http://www.portalinmobiliario.com/" + str(operacion) + "/" + str( tipo) + "/" + str( region ) + "?tp=6&op=2&ca=2&ts=1&dd=0&dh=6&bd=0&bh=6&or=&mn=1&sf=0&sp=0&pg=1" print(link) try: page2 = requests.get( link, headers={'User-Agent': agentCreator.generateAgent()}) tree2 = html.fromstring(page2.content) except: print("[SUPI] fail") paginas = tree2.xpath( '//*[@id="wrapper"]/section[2]/div/div/div[1]/article/div[1]/div[1]/div/div/text()[1]' ) if len(paginas) == 0: return pagsplit = (str(paginas[0]).split())[2] nrOfPubs = int(pagsplit.replace(".", "")) nrOfPbsPerPage = 25 nrPages = math.ceil(nrOfPubs / nrOfPbsPerPage) subsites = [] subsiteBasicUrl = (link)[:-1] for i in range(1, nrPages + 1): subsites.append(subsiteBasicUrl + str(i)) getInfo(subsites, d, h, lista, faillista, operacion, tipo, region)
def scrapCorredor(link): proxi = next(proxy_pool) response = requests.get(link, headers={'User-Agent': agentCreator.generateAgent()}) soup = BeautifulSoup(response.text, "lxml") valores = soup.find_all("td", {"class": "Valor"}) titulo = soup.find("h1") emails = [] for v in valores: if v.string is not None: if "@" in v.string: emails.append(v.string) insertCorredores(emails)
def publicacionExiste(link): try: page = requests.get( link, headers={'User-Agent': agentCreator.generateAgent()}) tree = html.fromstring(page.content) except: return False paginas = tree.xpath('//*[@id="short-desc"]/div/header/h1') if "finalizada" in page.text: return False elif len(paginas) != 0: return True else: return False time.sleep(0.3)
def getLast(operacion, tipo, region, proxi): #Obtiene el número de la última página con publicaciones #armar link a consultar dada una operacion, tipo, region link = 'https://www.portalinmobiliario.com/' + str(operacion) + '/' + str( tipo) + '/' + str( region) + '?ca=2&ts=1&mn=2&or=p-asc&pg=1&sf=0&sp=0&at=0' page2 = requests.get(link, headers={'User-Agent': agentCreator.generateAgent()}) tree2 = html.fromstring(page2.content) xpath = '//*[@id="PaginacionSuperior"]/div/ul/li[6]/a' last = tree2.xpath(xpath) try: last = last[0] except: for i in range(1, 5): xpath = '//*[@id="PaginacionSuperior"]/div/ul/li[' + str(6 - i) + ']/a' last = tree2.xpath(xpath) try: last = last[0] break except: continue try: last = last.attrib last = str(last) last = last.split('=') last = last[8] last = last.split(',') last = last[0] last = last[:-1] try: last = int(last) except: last = int(last[0]) except: last = 1 print("[SUPI] " + str(last)) return last
def getInfo(subsites, desde, hasta, lista, faillista, op, tip, reg): for j in range(desde, hasta): try: page2 = requests.get( subsites[j], headers={'User-Agent': agentCreator.generateAgent()}) tree2 = html.fromstring(page2.content) except: print("[SUPI] fail") lastRange = 25 for i in range(1, lastRange + 3): global a codeSite = '//*[@id="wrapper"]/section[2]/div/div/div[1]/article/div[3]/div[' + str( i) + ']/div[2]/div/div[1]/p[2]' nameSite = '//*[@id="wrapper"]/section[2]/div/div/div[1]/article/div[3]/div[' + str( i) + ']/div[2]/div/div[1]/h4/a' priceSite = '//*[@id="wrapper"]/section[2]/div/div/div[1]/article/div[3]/div[' + str( i) + ']/div[2]/div/div[2]/p/span' meterSite = '//*[@id="wrapper"]/section[2]/div/div/div[1]/article/div[3]/div[' + str( i) + ']/div[2]/div/div[3]/p/span' stateSite = '//*[@id="wrapper"]/section[2]/div/div/div[1]/article/div[3]/div[' + str( i) + ']/div[2]/div/div[1]/p[1]/span' code = tree2.xpath(codeSite) if len(code) == 0: codeSite = '//*[@id="wrapper"]/section[2]/div/div/div[1]/article/div[3]/div[' + str( i) + ']/div[2]/div/div[1]/p[3]' '//*[@id="wrapper"]/section[2]/div/div/div[1]/article/div[3]/div[1]/div[2]/div/div[1]/p[3]' code = tree2.xpath(codeSite) name = tree2.xpath(nameSite) price = tree2.xpath(priceSite) meters = tree2.xpath(meterSite) state = tree2.xpath(stateSite) if len(code) > 0: aux = [] code = (code[0]).text if ("Codigo" not in code) and ("Código" not in code): codeSite = '//*[@id="wrapper"]/section[2]/div/div/div[1]/article/div[3]/div[' + str( i) + ']/div[2]/div/div[1]/p[3]' code = tree2.xpath(codeSite) code = (code[0]).text try: code = int(code[8:]) except: print("[SUPI] fail") aux.append(code) newLink = str((name[0]).attrib) newLink = newLink[17:] newLink = newLink[:-4] if op == "arriendo": newLink = 'http://www.portalinmobiliario.com/arrien' + newLink else: newLink = 'http://www.portalinmobiliario.com/venta/' + newLink name = (name[0]).text price = (price[0]).text price = str(price) price = price[2:] try: price = float(price.replace('.', '')) if len(meters) > 0: meters = meters[0].text else: meters = 'missing' if '-' in meters: meters = meters.split('-') minMeters = (meters[0])[:-1] maxMeters = (meters[1])[:-3] maxMeters = maxMeters[1:] minMeters = (minMeters.replace('.', '')) maxMeters = (maxMeters.replace('.', '')) minMeters = float(minMeters.replace(',', '.')) maxMeters = float(maxMeters.replace(',', '.')) elif 'missing' in meters: minMeters = -1 maxMeters = -1 else: meters = meters[:-3] meters = (meters.replace('.', '')) meters = float(meters.replace(',', '.')) minMeters = meters maxMeters = meters except: try: l = faillista[-1] l = l + 1 faillista.append(l) print("[SUPI] fails:" + str(l)) except: l = 1 print("[SUPI] fails (price or meters):" + str(l)) faillista.append(l) print("[SUPI] continued") continue try: page3 = requests.get( newLink, headers={'User-Agent': agentCreator.generateAgent()}) tree3 = html.fromstring(page3.content) except: print("[SUPI] fail") addresSite = '//*[@id="wrapper"]/section/div/div/div[1]/article/div/div[2]/div[1]/div[2]/div[1]/div/div/p[3]/span[1]' address = tree3.xpath(addresSite) if len(address) == 0: addresSite = '//*[@id="wrapper"]/section/div/div/div[1]/article/div/div[2]/div[2]/div[2]/div[1]/p/span[1]' address = tree3.xpath(addresSite) if len(address) == 0: addresSite = '//*[@id="project-location"]/div/div/div[1]/div/div[1]/p/span[1]' address = tree3.xpath(addresSite) if len(address) > 0: try: address = address[0].text except AttributeError: address = '-' else: address = None latSite = '/html/head/meta[18]' lat = tree3.xpath(latSite) if len(lat) > 0: lat = str((lat[0]).attrib).split(':') lat = lat[3] lat = (lat[2:])[:-2] try: lat = float(lat) except: try: l = faillista[-1] l = l + 1 faillista.append(l) print("[SUPI] fails:" + str(l)) except: l = 1 print("[SUPI] fails (lat):" + str(l)) faillista.append(l) continue else: lat = None lonSite = '/html/head/meta[19]' lon = tree3.xpath(lonSite) if len(lon) > 0: lon = (((str((lon[0]).attrib).split(':'))[3])[2:])[:-2] try: lon = float(lon) except: try: l = faillista[-1] l = l + 1 print("[SUPI] fails:" + str(l)) print(l) except: l = 1 print("[SUPI] fails (lon):" + str(l)) faillista.append(l) continue else: lon = None dormSite = '//*[@id="wrapper"]/section/div/div/div[1]/article/div/div[2]/div[2]/div[2]/div[2]/p/text()[1]' dorms = tree3.xpath(dormSite) try: if len(dorms) > 0: dorms = str(dorms) dorms = dorms[2] dorms = float(dorms) else: dormSite = '//*[@id="wrapper"]/section/div/div/div[1]/article/div/div[2]/div[2]/div[1]/div[2]/p/text()[1]' dorms = tree3.xpath(dormSite) if len(dorms) > 0: dorms = str(dorms) dorms = dorms[2] dorms = float(dorms) else: dorms = None except AttributeError: dorms = None bathSite = '//*[@id="wrapper"]/section/div/div/div[1]/article/div/div[2]/div[2]/div[2]/div[2]/p/text()[2]' baths = tree3.xpath(bathSite) try: if len(baths) > 0: baths = str(baths) baths = baths[2] baths = float(baths) else: bathSite = '//*[@id="wrapper"]/section/div/div/div[1]/article/div/div[2]/div[2]/div[1]/div[2]/p/text()[2]' baths = tree3.xpath(bathSite) if len(baths) > 0: baths = str(baths) baths = baths[2] baths = float(baths) else: baths = None except AttributeError: baths = None r = session.get(newLink) mails = [] # corredor="no" # rtext=r.text # if "empresas/ficha" in rtext: # #no es dueño # corredor="si" # rtext=rtext.split(' ') # # telefonoVendedor = "No" # # for x,a in enumerate(rtext): # if 'telefonosVendedor' in a: # # telefonoVendedor=rtext[x+2] # telefonoVendedor=telefonoVendedor.replace('nbsp;','') # telefonoVendedor=telefonoVendedor.replace('"','') # telefonoVendedor=telefonoVendedor.replace('&','') # telefonoVendedor="+"+str(telefonoVendedor) # if ("span" in telefonoVendedor): # telefonoVendedor=rtext[x+3] # telefonoVendedor=str(telefonoVendedor) # telefonoVendedor=telefonoVendedor.replace("itemprop='telephone'>",'') # # for x,a in enumerate(rtext): # if 'emailVendedor' in a: # emailvendedor=rtext[x+2] # emailvendedor=emailvendedor.replace('\r\n','') # emailvendedor=emailvendedor.replace('"','') # dueno=[] # dueno.append(code) # dueno.append(emailvendedor) # if (corredor=="si"): # dueno.append("no") # dueno.append(telefonoVendedor) # dueno.append(emailvendedor) # dueno.append("no") # dueno.append(telefonoVendedor) # else: # dueno.append(esDueno(emailvendedor)) # dueno.append(telefonoVendedor) # dueno.append(emailvendedor) # dueno.append(esDueno(emailvendedor)) # dueno.append(telefonoVendedor) dateSite = '//*[@id="wrapper"]/section/div/div/div[1]/article/div/div[2]/div[1]/div[1]/div[2]/p[2]/strong' date = tree3.xpath(dateSite) if len(date) > 0: date = date[0].text date = date[11:] dateSplit = date.split('-') date = dateSplit[2] + '-' + dateSplit[1] + '-' + dateSplit[ 0] else: date = None split = subsites[j].split('/') operacion = split[3] tipo = split[4] split2 = split[5].split('?') region = split2[0] estacionamientos = 0 texts = [] for p in range(1, 20): try: path = '//*[@id="wrapper"]/section/div/div/div[1]/article/div/div[2]/div[2]/div[3]/div/div/text()[' + str( p) + ']' texto = tree3.xpath(path) texto = texto[0] texto = str(texto) texts.append(texto) except: continue bodegas = obtenerBodegas(texts) estacionamientos = obtenerEstacionamientos(texts) fechahoy = datetime.datetime.now() fechascrap = str(fechahoy.year) + '-' + str( fechahoy.month) + '-' + str(fechahoy.day) #verificar si es dueño y crear objeto dueño agency_path = '//*[@id="real_estate_agency"]' agency = tree3.xpath(agency_path) esPropiedario = "no" if len(agency) == 0: #no hay agency; es dueño. esPropiedario = "si" dueno = [] dueno.append(code) dueno.append(None) dueno.append(esPropiedario) phone_path = '//*[@id="root-app"]/div/div[1]/div[2]/section[1]/p[3]/span/span[1]/text()' phone = tree3.xpath(phone_path) if len(phone) > 0: dueno.append(str(phone[0])) else: phone_path = '//*[@id="root-app"]/div/div[1]/div[2]/section[1]/p[5]/span/span/text()' phone = tree3.xpath(phone_path) dueno.append(str(phone[0])) #fin sector dueño aux.append(name) aux.append(date) aux.append(fechascrap) aux.append(region) aux.append(address) aux.append(operacion) aux.append(tipo) aux.append(price) aux.append(dorms) aux.append(baths) aux.append(minMeters) aux.append(maxMeters) aux.append(estacionamientos) aux.append(bodegas) aux.append(lat) aux.append(lon) aux.append(newLink) aux.append(name) aux.append(date) aux.append(fechascrap) aux.append(region) aux.append(address) aux.append(operacion) aux.append(tipo) aux.append(price) aux.append(dorms) aux.append(baths) aux.append(minMeters) aux.append(maxMeters) aux.append(estacionamientos) aux.append(bodegas) aux.append(lat) aux.append(lon) aux.append(newLink) lista = lista + 1 print("[SUPI] " + str(tipo) + "s en " + operacion + " registradas/os en: " + str(region) + ": " + str(lista)) time.sleep(random.uniform(0, 0.5)) try: insertarDueno(dueno) except: abdcedf = 0 try: insertarPropiedad(aux) except: continue actualizar_checker(op, tip, reg, j)
def main(pagRec=1, regRec=1, isRecovery=False, ocr=None): regiones = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16] while (True): for reg in regiones: if isRecovery: if reg != regRec: continue link = "https://www.yapo.cl/atacama/inmuebles?ca=" + str( reg) + "_s&st=a&cg=1000" page = requests.get( link, headers={'User-Agent': agentCreator.generateAgent()}) tree = html.fromstring(page.content) last = tree.xpath('//*[@id="tabnav"]/li[2]/h2/span[2]') last = last[0].text last = last.split(' ') last = last[5] last = last.replace('.', '') last = int(last) last = int(last / 50) + 1 if isRecovery: isRecovery = False ran = range(pagRec, last) else: ran = range(1, last) for i in ran: link2 = link + "&o=" + str(i) session = HTMLSession() r = session.get(link2) links3 = [] duenos = [] for a in r.html.find('.title'): list = [] links3.append(a.links.pop()) for piece in r.html.find('.clean_links'): company_ad = piece.find('.company_ad') duenos.append(len(company_ad) == 0) props = zip(links3, duenos) for link3, dueno in props: codigo = -1 idregion = -1 comuna = "" tipo = "" titulo = "" operacion = "" preciouf = -1 preciopesos = -1 fechapublicacion = "" fechahoy = datetime.datetime.now() fechascrap = str(fechahoy.year) + '-' + str( fechahoy.month) + '-' + str(fechahoy.day) metrosmin = -1 metrosmax = -1 dormitorios = -1 banos = -1 descripcion = "" lat = -999 lon = -999 anoconstruccion = -1 ggcc = -1 estacionamientos = 0 esdueno = 0 if dueno: esdueno = 1 page = requests.get( link3, headers={'User-Agent': agentCreator.generateAgent()}) tree = html.fromstring(page.content) url = [] metatext = page.text metatext = metatext.split(' ') descripcion = [] savedescripcion = False saveimg = False og = True for texto in metatext: if og and 'og:image' in texto: saveimg = True og = False if 'img/yapo' in texto: saveimg = False if saveimg and 'img.yapo.cl/images' in texto: texto = texto.replace('content="', '') texto.replace('"', '') url.append(texto) if 'phone-url' in texto: texto = texto.split('"') texto = texto[1] auxPhone = texto auxPhone = 'https://www.yapo.cl' + auxPhone # try: # response = requests.get(auxPhone, headers={'User-Agent': agentCreator.generateAgent()}) # img = Image.open(BytesIO(response.content)) # img.save("auxphone.gif") # telefono=ocr("auxphone.gif") # except: # telefono='NN' telefono = 'NN' precio1 = tree.xpath( '//*[@id="content"]/section[1]/article/div[5]/div[1]/table/tbody/tr[1]/td/div/strong' ) precio2 = tree.xpath( '//*[@id="content"]/section[1]/article/div[5]/div[1]/table/tbody/tr[1]/td/div/span/span' ) '//*[@id="content"]/section[1]/article/div[5]/div[1]/table/tbody/tr[1]/td/div/strong' '//*[@id="content"]/section[1]/article/div[5]/div[1]/table/tbody/tr[1]/td/div/span/span' if len(precio1) < 0: continue if len(precio2) == 0: print("Error al sacar el precio en " + link) continue if ('$') in precio2[0].text: preciopesos = precio2[0].text preciouf = precio1[0].text else: preciopesos = precio1[0].text preciouf = precio2[0].text preciopesos = preciopesos.replace('.', '') preciopesos = preciopesos.replace('$', '') preciopesos = preciopesos.replace(' ', '') preciopesos = preciopesos.replace(')', '') preciopesos = preciopesos.replace('(', '') preciopesos = preciopesos.replace('*', '') preciopesos = int(preciopesos) preciouf = preciouf.replace('.', '') preciouf = preciouf.replace('$', '') preciouf = preciouf.replace(' ', '') preciouf = preciouf.replace(')', '') preciouf = preciouf.replace('(', '') preciouf = preciouf.replace('*', '') preciouf = preciouf.replace('UF', '') preciouf = preciouf.replace(',', '.') preciouf = float(preciouf) #extraccion codigo aux = link3.split('.') aux = aux[-2] aux = aux.split('_') codigo = int(aux[-1]) utag_data = tree.xpath("/html/body/script[1]/text()")[0] text = str(utag_data.split('=')[1]) text = text[:-5] + "}" try: value = json.loads(text) except: continue try: idregion = value["region_level2_id"].lower() except: pass try: comuna = value["region_level3"].lower() except: pass try: titulo = value["ad_title"].lower() except: pass try: if value["category_level2"] == "Vendo": operacion = "venta" elif value["category_level2"] == "Arriendo": operacion = "arriendo" elif value[ "category_level2"] == "Arriendo de temporada": operacion = "temporada" except: pass try: fechapublicacion = value["publish_date"].split(' ')[0] except: pass try: dormitorios = int(value["rooms"]) except: pass try: descripcion = value["description"] except: pass try: if int(value["geoposition_is_precise"]) == 1: pos = value["geoposition"].split(',') lat = float(pos[0]) lon = float(pos[1]) except: pass tabla = tree.xpath( """//*[@id="content"]/section[1]/article/div[5]/div[1]/table/tbody/tr""" ) tabla.pop(0) for row in tabla: rowname = row.find("th").text if rowname == "Tipo de inmueble": tipo = row.find("td").text elif rowname == "Superficie total": metrosmax = row.find("td").text.replace( '\n', '').replace('\t', '').split(' ')[0] elif rowname == "Superficie útil" or rowname == "Superficie construida": metrosmin = row.find("td").text.replace( '\n', '').replace('\t', '').split(' ')[0] elif rowname == "Baños": banos = row.find("td").text banos = int(str(banos.split(' ')[0])) elif rowname == "Estacionamiento": estacionamientos = row.find("td").text elif rowname == "Año de construcción": anoconstruccion = row.find("td").text elif rowname == "Gastos comunes": ggcc = row.find("td").text[2:] ggcc = ggcc.replace('.', '') ggcc = float(ggcc) try: propiedad = [] propiedad.append(codigo) propiedad.append(idregion) propiedad.append(comuna) propiedad.append(tipo.lower()) propiedad.append(titulo) propiedad.append(operacion.lower()) propiedad.append(preciouf) propiedad.append(preciopesos) propiedad.append(fechapublicacion) propiedad.append(fechascrap) propiedad.append(int(float(metrosmin))) propiedad.append(int(float(metrosmax))) propiedad.append(int(float(dormitorios))) propiedad.append(int(float(banos))) propiedad.append(int(float(estacionamientos))) propiedad.append(descripcion) propiedad.append(lat) propiedad.append(lon) propiedad.append(anoconstruccion) propiedad.append(ggcc) propiedad.append(link3) propiedad.append(esdueno) propiedad.append(telefono) propiedad.append(idregion) propiedad.append(comuna) propiedad.append(tipo.lower()) propiedad.append(titulo) propiedad.append(operacion.lower()) propiedad.append(preciouf) propiedad.append(preciopesos) propiedad.append(fechapublicacion) propiedad.append(fechascrap) propiedad.append(int(float(metrosmin))) propiedad.append(int(float(metrosmax))) propiedad.append(int(float(dormitorios))) propiedad.append(int(float(banos))) propiedad.append(int(float(estacionamientos))) propiedad.append(descripcion) propiedad.append(lat) propiedad.append(lon) propiedad.append(anoconstruccion) propiedad.append(ggcc) propiedad.append(link3) propiedad.append(esdueno) propiedad.append(telefono) except Exception as err: print("Error en propiedad:" + link + " \n " + str(err)) continue insertarPropiedad(propiedad) try: os.remove("auxphone.gif") except: pass print("[SYG] insertada propiedad id:" + str(propiedad[0]) + " " + str(i) + "/" + str(last)) time.sleep(random.uniform(1, 1.5)) actualizar_checker(operacion=operacion, tipo=tipo, region=idregion, pagina=i)
def crearFicha(sitio,id,mail,tipoficha): links=[] text2='' auxPhone=0 #Determinar tipo de informe pro=False interna=False full=False if tipoficha==2: pro=True elif tipoficha==3: interna=True elif tipoficha==4: interna=True pro=True #Chequear que sitio este bien sitio=sitio.lower() if('portal' in sitio): sitio='portal' elif('yapo' in sitio): sitio='yapo' else: text='Sitio ingresado es incorrecto. Favor ingresar portalinmobiliario o yapo.' return(text) #Chequear que mail este bien if ('@' not in mail): text='Email incorrecto. Favor ingresar correo válido.' return(text) if ('.' not in mail): text='Email incorrecto. Favor ingresar correo válido.' return(text) #sacar informacion de bbdd, y chequear que propiedad existe: propiedad=obtenerProp(id,sitio) if len(propiedad)<1: text='¨Propiedad no se encuentra en la base de datos.' return(text) else: propiedad=list(propiedad) nombre=str(propiedad[0]) region=str(propiedad[1]) regionP=region regionY=region if region=='15': regionP='metropolitana' if region=='metropolitana': regionY='15' operacion=str(propiedad[2]) tipo=str(propiedad[3]) precio=float(propiedad[4]) dormitorios=str(propiedad[5]) banos=str(propiedad[6]) metrosmin=str(propiedad[7]) metrosmax=str(propiedad[8]) estacionamientos=str(propiedad[9]) bodegas=str(propiedad[10]) lat=str(propiedad[11]) lon=str(propiedad[12]) link=str(propiedad[13]) if sitio=='portal': if operacion=='venta': comuna=str(link.split('/')[5]) comuna=comuna.replace('-'+str(regionP),'') comuna=comuna.replace('-',' ') comuna=comuna.capitalize() propiedad.append(comuna) else: comuna=str(link.split('/')[6]) comuna=comuna.replace('-metropolitana','') comuna=comuna.replace('-',' ') comuna=comuna.capitalize() propiedad.append(comuna) else: comuna=str(propiedad[14]) #Revisar si existe aun la publicacion if not pubPortalExiste.publicacionExiste(link): text='Propiedad ya no se encuentra disponible en el sitio.' return(text) #sacar informacion de la publicacion #sacar urls fotos portal matrixdescripcion=[] matrixcounter=0 matrixdescripcion.append('') if sitio=='portal': first=True url=[] page = requests.get(link, headers={'User-Agent': agentCreator.generateAgent()}) metatext=page.text metatext=metatext.split(' ') descripcion=[] savedescripcion=False for texto in metatext: if 'propiedad-descr' in texto: savedescripcion=True if '/div' in texto: savedescripcion = False if savedescripcion: descripcion.append(str(texto)) descripcion=descripcion[2:] print(descripcion) if not interna: for desc in descripcion: desc=desc.replace(' ','') desc=desc.replace('<br />',' ') desc=desc.replace('<br/>',' ') desc=desc.replace('<br>',' ') desc=desc.replace('<b/>','') desc=desc.replace('<b>','') desc=desc.replace('</b>','') desc=desc.replace('<br','') desc=desc.replace('/>','') desc=desc.replace('í','í') desc=desc.replace('é','é') desc=desc.replace('ó','ó') desc=desc.replace('á','á') desc=desc.replace('ú','ú') desc=desc.replace('ñ','ñ') desc=desc.replace('Ñ','Ñ') if "+56" in desc: desc="**" if len(desc)>=6: try: desc.replace('\n',"") int(desc) desc="**" except: pass if "@" in desc: desc="***" if ((len(matrixdescripcion[matrixcounter])+len(desc))>=78): matrixcounter+=1 matrixdescripcion.append('') if desc!= '': matrixdescripcion[matrixcounter]=matrixdescripcion[matrixcounter]+str(desc) else: if first: if desc!= '': matrixdescripcion[matrixcounter]=matrixdescripcion[matrixcounter]+str(desc) first=False else: if desc!= '': matrixdescripcion[matrixcounter]=matrixdescripcion[matrixcounter]+' '+str(desc) print(matrixdescripcion) for x,matrix in enumerate(matrixdescripcion): matrix=matrix.replace('<br />','\n') matrix=matrix.replace('<br/>','\n') matrix=matrix.replace('<br>','\n') matrix=matrix.replace('<b/>','') matrix=matrix.replace('<b>','') matrix=matrix.replace('</b>','') matrixdescripcion[x]=matrix descripcion='\n'.join(matrixdescripcion) propiedad.append(descripcion) else: descripcion=' '.join(descripcion) descripcion=descripcion.replace(' ','') descripcion=descripcion.replace('<br />','\n') descripcion=descripcion.replace('<br/>','\n') descripcion=descripcion.replace('<br>','\n') descripcion=descripcion.replace('<b/>','') descripcion=descripcion.replace('<b>','') descripcion=descripcion.replace('</b>','') descripcion=descripcion.replace('<br','') descripcion=descripcion.replace('/>','') descripcion=descripcion.replace('í','í') descripcion=descripcion.replace('é','é') descripcion=descripcion.replace('ó','ó') descripcion=descripcion.replace('á','á') descripcion=descripcion.replace('ú','ú') descripcion=descripcion.replace('ñ','ñ') descripcion=descripcion.replace('Ñ','Ñ') propiedad.append(descripcion) for meta in metatext: if 'https://image.portalinmobiliario.cl/Portal/Propiedades' in meta and '1200' in meta: meta=meta.split('"') url.append(str(meta[1])) #Sacar urls fotos yapo else: url=[] page = requests.get(link, headers={'User-Agent': agentCreator.generateAgent()}) metatext=page.text metatext=metatext.split(' ') descripcion=[] savedescripcion=False saveimg=False og=True for texto in metatext: if '<h4>Descripción</h4>' in texto: savedescripcion=True if og and 'og:image' in texto: saveimg=True og=False if 'img/yapo' in texto: saveimg=False if savedescripcion: descripcion.append(str(texto)) if '</div>' in texto: savedescripcion = False if saveimg and 'img.yapo.cl/images' in texto: texto=texto.replace('content="','') texto.replace('"','') url.append(texto) if 'phone-url' in texto: texto=texto.split('"') texto=texto[1] auxPhone=texto auxPhone='https://www.yapo.cl'+auxPhone descripcion=descripcion[1:] first=True print(descripcion) for desc in descripcion: desc=desc.replace('\n',' ') desc=desc.replace('<br />','\n') desc=desc.replace('</div>','\n') desc=desc.replace('<br>','\n') desc=desc.replace('<br','') desc=desc.replace('/>','') desc=desc.replace('itemprop="description">',"") desc=desc.replace('</p>','\n') desc=desc.replace("\t","") desc=desc.replace('<!','') desc=desc.replace('--','') desc=desc.replace(' ','') desc=desc.replace('\n',' ') if ((len(matrixdescripcion[matrixcounter])+len(desc))>=78): matrixcounter+=1 matrixdescripcion.append('') matrixdescripcion[matrixcounter]=matrixdescripcion[matrixcounter]+str(desc) else: if first: matrixdescripcion[matrixcounter]=matrixdescripcion[matrixcounter]+str(desc) first=False else: matrixdescripcion[matrixcounter]=matrixdescripcion[matrixcounter]+' '+str(desc) print(matrixdescripcion) descripcion='\n'.join(matrixdescripcion) propiedad.append(descripcion) try: print(auxPhone) response = requests.get(auxPhone, headers={'User-Agent': agentCreator.generateAgent()}) auxphone2=auxPhone img = Image.open(BytesIO(response.content)) img=img.convert('L') img=img.convert('1') img.save("auxphone.gif") auxPhone=1 except: pass lenfotos=len(url) if len(url)==0: print("la propiedad no cuenta con fotografias") else: print('total fotos: '+str(len(url))) for x,u in enumerate (url): u=u.replace('"','') response = requests.get(u) img = Image.open(BytesIO(response.content)) img.save(str(x)+" foto.jpg") if not interna: imagenDescripcion = Image.new('RGB', (456, 345), color = (255, 255, 255)) d = ImageDraw.Draw(imagenDescripcion) f= ImageFont.truetype('arial.ttf',12) d.text((0,0), descripcion,font=f, fill=(0,0,0)) imagenDescripcion.save('imagenDescripcion.png') datospro = [] if pro: comunaP = (comuna.replace(' ', '-') + '-'+str(region)).lower() listacomunas=[] listacomunas.append(comuna) propsP = reportes.from_portalinmobiliario(tipo, regionP,listacomunas, True) propsY = reportes.from_yapo(tipo, regionY,listacomunas, True, True) props = propsP + propsY if operacion=='venta': print("la comuna para calcular la rentabilidad promedio es:") print(comunaP) rentaPromedio = reportes.rentaPProm(tipo, float(dormitorios), float(banos), float(estacionamientos), comunaP) print("input tasacion ficha") print(tipo) print(float(lat)) print(float(lon)) print(float(metrosmin)) print(float(metrosmax)) print(float(dormitorios)) print(float(banos)) print(float(estacionamientos)) tasacionVenta = tb2.calcularTasacionData("venta", tipo, float(lat), float(lon), float(metrosmin),float(metrosmax),float(dormitorios), float(banos), float(estacionamientos), props) tasacionArriendo = tb2.calcularTasacionData("arriendo", tipo, float(lat), float(lon), float(metrosmin),float(metrosmax),float(dormitorios), float(banos), float(estacionamientos), props) precioV = tasacionVenta[0] * uf.getUf() precioA = tasacionArriendo[0] print("el precio tasado de venta inicial es: "+str(precioV)) print("el precio tasado de arriendo inicial es: "+str(precioA)) links=tasacionVenta[3] if precioV is None or precioV < 0.1: pro=False try: precioA = tasacionArriendo[0] rentaV = ((precioV - precio) / precio) except: pro=False text2='No se ha podido realizar tasación' print('fail 1') if precioA is None or precioA < 0.01: pro=False try: rentaA = (precioA * 12 / precio) print('succes 2.1') print(precioA) print(precioV) rentaPP = (precioA * 12 / precioV) print('succes 2.2') except: pro=False text2='No se ha podido realizar tasación' print('fail 2') if pro: if rentaA > 0.2: pro=False print('fail 3') if rentaPP < 1.2*rentaPromedio: try: print("[GeneradorReportes] renta pp muy baja, recalculando precio") print("precio anterior:"+str(precioV)) precioV = precioA * 12 / rentaPromedio rentaV = ((precioV - precio) / precio) rentaPP = (precioA * 12 / precioV) print("precio nuevo:"+str(precioV)) except: pro=False text2='No se ha podido realizar tasación' print('fail 4') if rentaPP > 0.15: try: precioV = precioA * 12 / 0.15 rentaV = ((precioV - precio) / precio) except: pro=False text2='No se ha podido realizar tasación' print('fail 52') if rentaA < 0: pro=False if pro: # precio venta tasado datospro.append(precioV) # rentabilidad de venta datospro.append(float(rentaV)) # precio arriendo tasado datospro.append(precioA) # rentabilidad de arriendo datospro.append(float(rentaA)) else: try: tasacionArriendo = tb2.calcularTasacionData("arriendo", tipo, float(lat), float(lon), float(metrosmin),float(metrosmax),float(dormitorios), float(banos), float(estacionamientos), props) except: pro=False text2='No se ha podido realizar tasación' print('fail 6') try: precioA = tasacionArriendo[0] links=tasacionArriendo[3] except: pro=False text2='No se ha podido realizar tasación' print('fail 72') if pro: if precioA is None or precioA < 0.01: pro = False text2='No se ha podido realizar tasación' print('fail 8') if pro: # precio arriendo tasado datospro.append(precioA) # rentabilidad de arriendo datoscontacto = [] if interna: if sitio=='portal': try: email, telefono, dueno = reportes.getDatosDueno(str(id)) except: email = "NN" telefono = "NN" dueno = "NN" else: email = "NN" if auxPhone == 1: telefono=auxphone2 else: telefono = "NN" dueno = 'NN' datoscontacto.append(email) datoscontacto.append(telefono) datoscontacto.append(dueno) #Crear PDF if interna: nombrearchivo="Ficha Propiedad Sitio:"+str(sitio)+" Id:"+str(id)+".pdf" else: nombrearchivo="Ficha Propiedad Sitio:"+str(sitio)+", "+str(operacion)+", "+str(tipo)+", "+str(region)+", "+str(comuna)+".pdf" print(nombrearchivo) pdfCreatorFichas.crearPdfFicha(nombrearchivo,id,propiedad,lenfotos,pro,datospro,interna,datoscontacto,regionP,links) print("pdf generado con exito") #Enviar PDF sendmail.sendMail(mail,"",nombrearchivo) #Eliminar del servidor if len(url)==0: pass else: for x,u in enumerate (url): os.remove(str(x)+" foto.jpg") try: os.remove("auxphone.gif") except: pass if not interna: try: os.remove("imagenDescripcion.png") except: pass os.remove(nombrearchivo) #Retornar exito text = "Ficha creada para la propiedad: "+str(id)+" obtenida del sitio: "+str(sitio)+", enviada con éxito al correo: "+str(mail)+"." if text2!='': text=text2+'. '+text return(text)
def main(): # x = [i for i in range(1000000)] # random.shuffle(x) generalList = list(range(1, 7250000)) scraped = get_scraped() print("Deleting scraped Values from General List") #generalList = [i for i in generalList if i not in scraped] print("Deleting scraped Values from General List") for a, x in enumerate(scraped): if x in generalList: print(str(a) + "/" + str(len(scraped))) generalList.remove(x) else: print("Value: " + str(x) + " not in general list") print("Scraped Values Deleted") for i in generalList: print("Getting ID: " + str(i)) masterVar = sacarVariablesBD() headers = { 'sec-fetch-mode': 'cors', 'cookie': 'X-DATA=98873086-bacb-4c67-9630-f921f2f817dd; _gcl_au=1.1.1050132614.1567703513; _fbp=fb.1.1567703512776.1834989938; _ga=GA1.2.1687249867.1567703522; _gid=GA1.2.1630980933.1567703522; NPS_93546e30_last_seen=1567703521710; __RequestVerificationToken=bBMzbT0DpwlchpCzyFgptd4oA3sdZ3i-IiVhoujkeSgL_P2MEpiCjUSSpkNaxzAiEYh2kAkZ4YmymKzYKtkIkWgt2TjcZ0yty3o7KNb-NvY1; optimizelyEndUserId=oeu1567703541845r0.0295507821834311; optimizelySegments=%7B%222204271535%22%3A%22gc%22%2C%222215970531%22%3A%22false%22%2C%222232940041%22%3A%22direct%22%7D; optimizelyBuckets=%7B%7D; __insp_wid=2107690165; __insp_nv=true; __insp_targlpu=aHR0cHM6Ly93d3cudG9jdG9jLmNvbS9wcm9waWVkYWRlcy9jb21wcmFudWV2by9kZXBhcnRhbWVudG8vcHJvdmlkZW5jaWEvbW9sbGVyLWVkaWZpY2lvLWx5b24tMjU1MC8xMTE5NDg5P289bGlzdGFkb19jYWx1Z2FfaW1n; __insp_targlpt=RGVwYXJ0YW1lbnRvcyBOdWV2b3MgYSBsYSB2ZW50YSBlbiBQcm92aWRlbmNpYSwgZGUgTW9sbGVyICYgUMOpcmV6LUNvdGFwb3MgUy5BLiwgTW9sbGVyIEVkaWZpY2lvIEx5b24gMjU1MA%3D%3D; __insp_norec_sess=true; __atuvc=9%7C36; __atuvs=5d71478ffef8eeaa008; __insp_slim=1567706242969; X-DATA-NPSW={"CantidadVisitas":1,"FechaCreacion":"2019-09-05T14:11:46.4457584-03:00","FechaUltimoIngreso":"2019-09-05T15:01:55.0949289-03:00","Detalles":[{"TipoVistaNPS":1,"Cantidad":9,"FechaUltimoIngreso":"2019-09-05T14:37:14.2930896-03:00"},{"TipoVistaNPS":2,"Cantidad":3,"FechaUltimoIngreso":"2019-09-05T14:54:05.5199312-03:00"},{"TipoVistaNPS":3,"Cantidad":23,"FechaUltimoIngreso":"2019-09-05T15:01:55.0949289-03:00"}]}; optimizelyPendingLogEvents=%5B%5D; _gat=1; mp_29ae90688062e4e2e6d80b475cef8685_mixpanel=%7B%22distinct_id%22%3A%20%2216d0269ab023a9-0be21a1087fb92-5373e62-15f900-16d0269ab032ad%22%2C%22%24device_id%22%3A%20%2216d0269ab023a9-0be21a1087fb92-5373e62-15f900-16d0269ab032ad%22%2C%22%24initial_referrer%22%3A%20%22https%3A%2F%2Fwww.toctoc.com%2Fresultados%2Fmapa%2Fcompra%2Fcasa-departamento%2Fmetropolitana%2Fprovidencia%2F%3Fmoneda%3D2%26precioDesde%3D0%26precioHasta%3D0%26dormitoriosDesde%3D%26dormitoriosHasta%3D%26banosDesde%3D0%26banosHasta%3D0%26estado%3D0%26disponibilidadEntrega%3D%26numeroDeDiasTocToc%3D0%26superficieDesdeUtil%3D0%26superficieHastaUtil%3D0%26superficieDesdeConstruida%3D0%26superficieHastaConstruida%3D0%26superficieDesdeTerraza%3D0%26superficieHastaTerraza%3D0%26superficieDesdeTerreno%3D0%26superficieHastaTerreno%3D0%26ordenarPor%3D0%26pagina%3D1%26paginaInterna%3D1%26zoom%3D15%26idZonaHomogenea%3D0%26atributos%3D%26texto%3DProvidencia%2C%2520Santiago%26viewport%3D-33.44984360032895%2C-70.64003981896111%2C-33.40916593228432%2C-70.57843955836275%26idPoligono%3D47%26publicador%3D0%26temporalidad%3D0%22%2C%22%24initial_referring_domain%22%3A%20%22www.toctoc.com%22%7D', 'x-xsrf-token': 'YNj3aaAeMW0L0TXabCnxaqXi1DYGaDmOPX_V02LSjZhB7LU2zUh-oyTIzVuH1ez2jrVFTyqcb301oOyAbK9zPhybbM8hsZ_LhHdPCeACE0U1', 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'es-419,es;q=0.9', 'user-agent': agentCreator.generateAgent(), 'accept': '*/*', 'referer': 'https://www.toctoc.com/propiedades/vivienda/a/a/a/' + str(id), 'authority': 'www.toctoc.com', 'x-requested-with': 'XMLHttpRequest', 'sec-fetch-site': 'same-origin' } params = (('id', str(i)), ) try: response = requests.get( 'https://www.toctoc.com/api/propiedades/bienRaiz/vivienda', headers=headers, params=params, proxies=get_proxy()) json_data = json.loads(response.text) except: print("Unable to get response") continue try: bien = json_data['BienRaiz'] print("Bien parseado exitosamente") except: print("error al extraer data") continue try: propiedad_filtrada = dict() process(bien, propiedad_filtrada) except: print("error al crear diccionario") continue try: for b in propiedad_filtrada.items(): if b[0] not in masterVar: # si la variable no esta en bd tipo = "TEXT" if type(b[1]) is int: tipo = "INT" elif type(b[1]) is float: tipo = "FLOAT" agregarColumna(b[0], tipo) except: print("error al procesar data") continue try: insertarPropiedad(propiedad_filtrada) except: print("error al insertar propiedad a la BBDD") continue
def scraper(tipo,region,a): fechahoy = datetime.datetime.now() fechascrap=str(fechahoy.year)+'-'+str(fechahoy.month)+'-'+str(fechahoy.day) try: link = "https://www.portalinmobiliario.com/venta/"+tipo+"/"+region+"?ca=1&ts=1&mn=1&or=&sf=0&sp=0&at=0&pg=" + str(a) page = requests.get(link, timeout=20, headers={'User-Agent': agentCreator.generateAgent()}) except: return print("continue") for j in range (1,28): proyecto = [] id=None nombre=None tipo=None comuna=None barrio=None direccion=None lat=None lon=None entrega=None propietario=None construye=None arquitecto=None propietario=None vende=None bodega=None bdesde=None bhasta=None bprom=None estacionamiento=None edesde=None ehasta=None eprom=None link2=None tree = html.fromstring(page.content) link2=tree.xpath('//*[@id="wrapper"]/section[2]/div/div/div[1]/article/div[3]/div['+str(j)+']/div[2]/div/div[1]/h4/a') try: link2=link2[0] except: continue link2=str(link2.attrib) link2=link2.split(': ') link2=link2[1] link2=str(link2) link2=link2[2:-2] link2 = "https://www.portalinmobiliario.com/" + link2 try: page2 = requests.get(link2, timeout=30, headers={'User-Agent': agentCreator.generateAgent()}) except: continue print("continue") tree2 = html.fromstring(page2.content) bye=tree2.xpath('//*[@id="project-descr"]/div/div[3]/div/p') try: bye=bye[0] bye=bye.text if ("no" in bye): if ("UF" in bye): try: byes=bye.split(' ') byen=0 for i in byes: if ("bodega" in i): if ("(desde" in byes[byen+1]): bdesde=byes[byen+3] if ("," in bdesde): bdesde=bdesde[:-1] if (")" in bdesde): bdesde=bdesde[:-1] else: bprom=byes[byen+2] if ("," in bprom) or ("." in bprom): bprom=bprom[:-1] if (")" in bprom): bprom=bprom[:-1] if ("hasta" in byes[byen+4]): bhasta=byes[byen+6] if ("," in bhasta) or ("." in bhasta): bhasta=bhasta[:-1] if (")" in bhasta): bhasta=bhasta[:-1] if ("estacionamiento" in i): if ("(desde" in byes[byen+1]): edesde=byes[byen+3] if ("," in edesde) or ("." in edesde): edesde=edesde[:-1] if (")" in edesde): edesde=edesde[:-1] else: eprom=byes[byen+2] if ("," in eprom) or ("." in eprom): eprom=eprom[:-1] if (")" in eprom): eprom=eprom[:-1] if ("hasta" in byes[byen+4]): ehasta=byes[byen+6] if ("," in ehasta) or ("." in ehasta): ehasta=ehasta[:-1] if (")" in ehasta): ehasta=ehasta[:-1] if ")" in ehasta: ehasta.split(")") ehasta=ehasta[0] byen=byen+1 bodega=0 estacionamiento=0 except: bodega = 0 estacionamiento = 0 else: bodega=0 estacionamiento=0 else: bodega=1 estacionamiento=1 try: bprom=(float(bdesde)+float(bhasta))/2 except: try: bprom=float(bprom) except: bprom=None try: eprom = (float(edesde) + float(ehasta)) / 2 except: eprom=None try: bdesde=float(bdesde) except: bdesde=None try: bhasta=float(bhasta) except: bhasta=None try: edesde = float(edesde) except: edesde=None try: ehasta = float(ehasta) except: ehasta=None try: eprom = float(eprom) except: eprom=None try: bodega=float(bodega) except: bodega=None try: estacionamiento=float(estacionamiento) except: estacionamiento=None byen=0 byes = bye.split(' ') for j in byes: if ("incluye") in j: if ("no" not in byes[byen-1]) or (byen==0): if ("estacionamiento" in byes[byen+1]): estacionamiento=1 if ("y" in byes[byen+2]): if("bodega" in byes[byen+3]): bodega=1 if("bodega" in byes[byen+4]): bodega=float(byes[byen+3]) if ("estacionamiento") in byes[byen+2]: try: estacionamiento=float(byes[byen+1]) except: estacionamiento=0 if ("y" in byes[byen+3]): if("bodega" in byes[byen+4]): bodega=1 if("bodega" in byes[byen+5]): try: bodega=float(byes[byen+4]) except: bodega=0 if ("bodega" in byes[byen+1]): bodega=1 if ("y" in byes[byen+2]): if("estacionamiento" in byes[byen+3]): estacionamiento=1 if("estacionamiento" in byes[byen+4]): estacionamiento=float(byes[byen+3]) if ("bodega") in byes[byen+2]: try: bodega=float(byes[byen+1]) except: bodega=0 if ("y" in byes[byen+3]): if("estacionamiento" in byes[byen+4]): estacionamiento=1 if("estacionamiento" in byes[byen+5]): try: estacionamiento=float(byes[byen+4]) except: estacionamiento=0 else: byen=byen+1 except: bodega=0 estacionamiento=0 try: bodega=int(bodega) bdesde=float(bdesde) bhasta=float(bhasta) bprom=float(bprom) estacionamiento=int(estacionamiento) edesde=float(edesde) ehasta=float(ehasta) eprom=float(eprom) except: alfa=None tester=tree2.xpath('//*[@id="project-descr"]/div/div[4]/div[2]/div/div[1]/strong') validator=4 try: tester=tester[0].text except: validator=5 for v in range (1,6): tester=tree2.xpath('//*[@id="project-descr"]/div/div['+str(validator)+']/div[2]/div/div['+str(v)+']/strong') try: if("Fecha" in tester[0].text): entrega=tree2.xpath('//*[@id="project-descr"]/div/div['+str(validator)+']/div[2]/div/div['+str(v)+']/text()') entrega=entrega[0] entrega=str(entrega) entrega=entrega[1:] if ("Propietario" in tester[0].text): propietario =tree2.xpath('//*[@id="project-descr"]/div/div['+str(validator)+']/div[2]/div/div['+str(v)+']/text()') propietario=propietario[0] propietario=str(propietario) propietario=propietario[1:] if ("Arquitecto" in tester[0].text): arquitecto=tree2.xpath('//*[@id="project-descr"]/div/div['+str(validator)+']/div[2]/div/div['+str(v)+']/text()') arquitecto=arquitecto[0] arquitecto=str(arquitecto) arquitecto=arquitecto[1:] if ("Construye" in tester[0].text): construye=tree2.xpath('//*[@id="project-descr"]/div/div['+str(validator)+']/div[2]/div/div['+str(v)+']/text()') construye=construye[0] construye=str(construye) construye=construye[1:] if ("Vende" in tester[0].text): vende=tree2.xpath('//*[@id="project-descr"]/div/div['+str(validator)+']/div[2]/div/div['+str(v)+']/text()') vende=vende[0] vende=str(vende) vende=vende[1:] except: continue session = HTMLSession() r = session.get(link2, timeout=20) script=r.html.find('.page-project') texto=script[0] texto=texto.text try: texto=texto.split(',') except: continue b=0 for t in texto: if ("lat") in t: try: lat=texto[b] if ("Nombre") not in t: lat=lat.split(': ') lat=lat[1] lat=lat.split(' ') lat=lat[0] lat=float(lat) lon=texto[b+1] lon=lon.split(' ') lon=lon[2] lon=float(lon) id=texto[b+1] id=id.split(':') id=id[2] id=int(id) nombre=texto[b+2] nombre=nombre.split(':') nombre=nombre[1] nombre=nombre[1:-1] tipo=texto[b+3] tipo=tipo.split(':') tipo=tipo[1] tipo=tipo[1:-1] direccion=texto[b+5] direccion=direccion.split(':') direccion=direccion[1] direccion=direccion[1:] if "?" in texto[b+7]: comuna=texto[b+6] comuna=comuna[1:-1] else: comuna=texto[b+8] comuna=comuna[1:-1] barrio=texto[b+7] barrio=barrio[1:] except: b=b+1 continue b=b+1 a=0 proyecto.append(id) proyecto.append(nombre) proyecto.append(tipo) proyecto.append(comuna) proyecto.append(barrio) proyecto.append(direccion) proyecto.append(lat) proyecto.append(lon) proyecto.append(entrega) proyecto.append(propietario) proyecto.append(arquitecto) proyecto.append(construye) proyecto.append(vende) proyecto.append(bodega) proyecto.append(bdesde) proyecto.append(bhasta) proyecto.append(bprom) proyecto.append(estacionamiento) proyecto.append(edesde) proyecto.append(ehasta) proyecto.append(eprom) proyecto.append(link2) proyecto.append(fechascrap) proyecto.append(fechascrap) print(len(proyecto)) print(proyecto) insertarProyecto(proyecto) time.sleep(random.uniform(0.5,1.5)) for t in texto: if ("Numero" in t): try: propiedad = [] n=str(texto[a]) try: n=n.split(':') n=str(n[1]) n=n[1:-1] except: n="nn" try: id3=(int(n)*100000) id3=id3+id except: continue precio=str(texto[a+1]) precio=precio.split(":") precio=str(precio[1]) try: precio=float(precio) except: precio=None dormitorios=str(texto[a+3]) dormitorios=dormitorios.split(":") dormitorios=str(dormitorios[1]) try: dormitorios=int(dormitorios) except: dormitorios=None banos=str(texto[a+4]) banos=banos.split(":") banos=str(banos[1]) banos=int(banos) piso=str(texto[a+5]) piso=piso.split(":") piso=str(piso[1]) try: piso=int(piso) except: piso=None orientacion=str(texto[a+6]) orientacion=orientacion.split(":") orientacion=str(orientacion[1]) orientacion=orientacion[1:-1] util=str(texto[a+8]) util=util.split(":") util=str(util[1]) try: util=float(util) except: util=None total=str(texto[a+9]) total=total.split(":") total=str(total[1]) try: total=float(total) except: total=None terraza=str(texto[a+10]) terraza=terraza.split(":") terraza=str(terraza[1]) try: terraza=float(terraza) except: terraza=None propiedad.append(id) propiedad.append(id3) propiedad.append(n) propiedad.append(precio) propiedad.append(dormitorios) propiedad.append(banos) propiedad.append(piso) propiedad.append(orientacion) propiedad.append(util) propiedad.append(total) propiedad.append(terraza) propiedad.append(fechascrap) print(id) print(id3) print(n) print(precio) print(dormitorios) print(banos) print(piso) print(orientacion) print(util) print(total) print(terraza) print(fechascrap) propiedad.append(fechascrap) insertarDepto(propiedad) except: continue a=a+1 sleep(5) sleep(120)
soup = BeautifulSoup(response.text, "lxml") valores = soup.find_all("td", {"class": "Valor"}) titulo = soup.find("h1") emails = [] for v in valores: if v.string is not None: if "@" in v.string: emails.append(v.string) insertCorredores(emails) for id in range(1,219): proxi=next(proxy_pool) link = "https://www.portalinmobiliario.com/empresas/corredoraspresentes.aspx?p=" + str(id) print(link) response = requests.get(link, headers={'User-Agent': agentCreator.generateAgent()}) soup = BeautifulSoup(response.text, "lxml") id = soup.find("table", {"id": "ContentPlaceHolder1_ListViewCorredorasPresentes_groupPlaceholderContainer"}) links = id.find_all("a") linkList = [] for l in links: fullLink = "https://www.portalinmobiliario.com" + str(l.get('href')) linkList.append(fullLink) for l in linkList: scrapCorredor(l) timeDelay = random.randrange(0, 1) time.sleep(timeDelay)
megamatrix = [] x = [i for i in range(1000000)] shuffle(x) for id in x: proxi = next(proxy_pool) print(proxi) headers = { 'cookie': 'X-DATA=2f5b2813-edf8-4b34-b07f-4087d288447f; NPS_93546e30_last_seen=1547558386874; _ga=GA1.2.989405458.1547558387; _gid=GA1.2.729091738.1547558387; NPS_93546e30_throttle=1547561987573; _fbp=fb.1.1547558388537.186150725; __RequestVerificationToken=86oRqQRziKy8hobVQw-bVcKUULRhKk0hFAUed5-63LKGrmXRJRKA0crNEPPaQTuaiiSjG9--AbVeffGENLIzkSOx8Hib95IdE4zhQsVcxuc1; optimizelyEndUserId=oeu1547558412070r0.6528189885507383; optimizelySegments=^%^7B^%^222204271535^%^22^%^3A^%^22gc^%^22^%^2C^%^222215970531^%^22^%^3A^%^22false^%^22^%^2C^%^222232940041^%^22^%^3A^%^22direct^%^22^%^7D; optimizelyBuckets=^%^7B^%^7D; __insp_wid=2107690165; __insp_slim=1547560739491; __insp_nv=true; __insp_targlpu=aHR0cHM6Ly93d3cudG9jdG9jLmNvbS9wcm9waWVkYWRlcy92aXZpZW5kYS9kZXBhcnRhbWVudG8vbGFzLWNvbmRlcy9jYW1pbm8tc2FuLWZyYW5jaXNjby1kZS1hc2lzLTExODAvNzI2MDE^%^3D; __insp_targlpt=VG9kYSBwcm9waWVkYWQgdGllbmUgc3UgcHJlY2lv; __insp_norec_sess=true; __atuvc=2^%^7C3; __atuvs=5c3de724c5463937000; X-DATA-NPSW=^{^\\^CantidadVisitas^\\^:1,^\\^FechaCreacion^\\^:^\\^2019-01-15T10:19:40.6966909-03:00^\\^,^\\^FechaUltimoIngreso^\\^:^\\^2019-01-15T11:02:06.4051203-03:00^\\^,^\\^Detalles^\\^:^[^{^\\^TipoVistaNPS^\\^:1,^\\^Cantidad^\\^:1,^\\^FechaUltimoIngreso^\\^:^\\^2019-01-15T10:19:40.6966909-03:00^\\^^},^{^\\^TipoVistaNPS^\\^:2,^\\^Cantidad^\\^:1,^\\^FechaUltimoIngreso^\\^:^\\^2019-01-15T10:20:09.9355287-03:00^\\^^},^{^\\^TipoVistaNPS^\\^:3,^\\^Cantidad^\\^:5,^\\^FechaUltimoIngreso^\\^:^\\^2019-01-15T11:02:06.4051203-03:00^\\^^}^]^}; _gat=1; mp_29ae90688062e4e2e6d80b475cef8685_mixpanel=^%^7B^%^22distinct_id^%^22^%^3A^%^20^%^2216851ab60b688d-08d1095668adbc-b781636-15f900-16851ab60b745d^%^22^%^2C^%^22^%^24device_id^%^22^%^3A^%^20^%^2216851ab60b688d-08d1095668adbc-b781636-15f900-16851ab60b745d^%^22^%^2C^%^22^%^24initial_referrer^%^22^%^3A^%^20^%^22https^%^3A^%^2F^%^2Fwww.toctoc.com^%^2F^%^22^%^2C^%^22^%^24initial_referring_domain^%^22^%^3A^%^20^%^22www.toctoc.com^%^22^%^7D; optimizelyPendingLogEvents=^%^5B^%^5D', 'x-xsrf-token': 'Ci7HAoA5M9U6itfuSvADh8YKudxIkLpWi4s_UMi7fMAMicuFnbjTdo2hgaPih-aOvxqO-LFBmNRURWRjnaikN7MeqzGnkuf7zGgiBzNEjXY1', 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'es-ES,es;q=0.9', 'user-agent': agentCreator.generateAgent(), 'accept': '*/*', 'referer': 'https://www.toctoc.com/propiedades/vivienda/departamento/las-condes/camino-san-francisco-de-asis-1180/72601', 'authority': 'www.toctoc.com', 'x-requested-with': 'XMLHttpRequest', } params = (('id', id), ) try: response = requests.get( 'https://www.toctoc.com/api/propiedades/bienRaiz/vivienda', headers=headers, params=params, proxies={
def crearFicha(sitio, id, mail, tipoficha): links = [] text2 = '' auxPhone = 0 #Determinar tipo de informe pro = False interna = False financiera = False textmail = '' ufn = uf.getUf() if tipoficha > 4: financiera = True tipoficha = tipoficha - 4 if tipoficha == 2: pro = True elif tipoficha == 3: interna = True elif tipoficha == 4: interna = True pro = True #Chequear que sitio este bien sitio = sitio.lower() if ('portal' in sitio): sitio = 'portal' elif ('yapo' in sitio): sitio = 'yapo' else: text = 'Sitio ingresado es incorrecto. Favor ingresar portalinmobiliario o yapo.' return (text) #Chequear que mail este bien if ('@' not in mail): text = 'Email incorrecto. Favor ingresar correo válido.' return (text) if ('.' not in mail): text = 'Email incorrecto. Favor ingresar correo válido.' return (text) #sacar informacion de bbdd, y chequear que propiedad existe: propiedad = obtenerProp(id, sitio) print(propiedad) if len(propiedad) < 1: if sitio == 'portal': link = "https://www.portalinmobiliario.com/" + str(id) else: link = "https://www.yapo.cl/region_metropolitana/" + str(id) if not pubPortalExiste.publicacionExiste( link) and not pubYapoExiste.publicacionExiste(link): text = '¨Propiedad no se encuentra en la base de datos.' return (text) elif sitio == "portal": pass else: if obtainPropFromYapo(link) is not False: propiedad = obtainPropFromYapo(link) else: regYapoDict = { "metropolitana": "15", "valparaiso": "6", "Valparaíso": "6", "arica": "1", "iquique": "2", "antofagasta": "3", "atacama": "4", "coquimbo": "5", "ohiggins": "7", "maule": "8", "ñuble": "16", "biobio": "9", "araucania": "10", "los Rios": "11", "los Lagos": "12", "aysen": "13", "magallanes": "14", } propiedad = list(propiedad) region = str(propiedad[1]) regionP = region regionY = regYapoDict[region.lower()] if region == '15': regionP = 'metropolitana' if region == 'metropolitana': regionY = '15' operacion = str(propiedad[2]) tipo = str(propiedad[3]) precio = float(propiedad[4]) dormitorios = str(propiedad[5]) banos = str(propiedad[6]) metrosmin = str(propiedad[7]) metrosmax = str(propiedad[8]) estacionamientos = str(propiedad[9]) bodegas = str(propiedad[10]) lat = str(propiedad[11]) lon = str(propiedad[12]) link = str(propiedad[13]) if sitio == 'portal': if operacion == 'venta': comuna = str(link.split('/')[5]) comuna = comuna.replace('-' + str(regionP), '') comuna = comuna.replace('-', ' ') comuna = comuna.capitalize() propiedad.append(comuna) else: comuna = str(link.split('/')[6]) comuna = comuna.replace('-metropolitana', '') comuna = comuna.replace('-', ' ') comuna = comuna.capitalize() propiedad.append(comuna) else: comuna = str(propiedad[14]) #Revisar si existe aun la publicacion if not pubPortalExiste.publicacionExiste(link): text = 'Propiedad ya no se encuentra disponible en el sitio.' return (text) #sacar informacion de la publicacion #sacar urls fotos portal matrixdescripcion = [] matrixcounter = 0 matrixdescripcion.append('') if sitio == 'portal': first = True url = [] page = requests.get( link, headers={'User-Agent': agentCreator.generateAgent()}) metatext = page.text metatext = metatext.split(' ') descripcion = [] savedescripcion = False for texto in metatext: if 'item-description__text' in texto: savedescripcion = True if '/div' in texto: if savedescripcion: descripcion.append(str(texto)) savedescripcion = False if savedescripcion: descripcion.append(str(texto)) descripcion2 = descripcion.copy() first = (descripcion2[0]) first = first.split(">") print(first) first = first[2] descripcion[0] = first last = descripcion2[-1] last = last.split("<") last = last[0] descripcion[-1] = last #descripcion=descripcion[2:] print(descripcion) descripcion = list(descripcion) if not interna: for desc in descripcion: desc = desc.replace(' ', '') desc = desc.replace('<br />', ' ') desc = desc.replace('<br/>', ' ') desc = desc.replace('<br>', ' ') desc = desc.replace('<b/>', '') desc = desc.replace('<b>', '') desc = desc.replace('</b>', '') desc = desc.replace('<br', '') desc = desc.replace('/>', '') desc = desc.replace('í', 'í') desc = desc.replace('é', 'é') desc = desc.replace('ó', 'ó') desc = desc.replace('á', 'á') desc = desc.replace('ú', 'ú') desc = desc.replace('ñ', 'ñ') desc = desc.replace('Ñ', 'Ñ') if "+56" in desc: desc = "**" if len(desc) >= 6: try: desc.replace('\n', "") int(desc) desc = "**" except: pass if "@" in desc: desc = "***" if ((len(matrixdescripcion[matrixcounter]) + len(desc)) >= 78): matrixcounter += 1 matrixdescripcion.append('') if desc != '': matrixdescripcion[matrixcounter] = matrixdescripcion[ matrixcounter] + str(desc) else: if first: if desc != '': matrixdescripcion[ matrixcounter] = matrixdescripcion[ matrixcounter] + str(desc) first = False else: if desc != '': matrixdescripcion[ matrixcounter] = matrixdescripcion[ matrixcounter] + ' ' + str(desc) print(matrixdescripcion) for x, matrix in enumerate(matrixdescripcion): matrix = matrix.replace('<br />', '\n') matrix = matrix.replace('<br/>', '\n') matrix = matrix.replace('<br>', '\n') matrix = matrix.replace('<b/>', '') matrix = matrix.replace('<b>', '') matrix = matrix.replace('</b>', '') matrixdescripcion[x] = matrix descripcion = '\n'.join(matrixdescripcion) propiedad.append(descripcion) else: descripcion = ' '.join(descripcion) descripcion = descripcion.replace(' ', '') descripcion = descripcion.replace('<br />', '\n') descripcion = descripcion.replace('<br/>', '\n') descripcion = descripcion.replace('<br>', '\n') descripcion = descripcion.replace('<b/>', '') descripcion = descripcion.replace('<b>', '') descripcion = descripcion.replace('</b>', '') descripcion = descripcion.replace('<br', '') descripcion = descripcion.replace('/>', '') descripcion = descripcion.replace('í', 'í') descripcion = descripcion.replace('é', 'é') descripcion = descripcion.replace('ó', 'ó') descripcion = descripcion.replace('á', 'á') descripcion = descripcion.replace('ú', 'ú') descripcion = descripcion.replace('ñ', 'ñ') descripcion = descripcion.replace('Ñ', 'Ñ') propiedad.append(descripcion) print(propiedad) for meta in metatext: if 'data-full-images' in meta: meta = meta.split(';') for met in meta: if 'mlstatic' in met: met = met.split('&') met = met[0] met = met.replace(".webp", ".jpg") url.append(str(met)) #Sacar urls fotos yapo else: url = [] page = requests.get( link, headers={'User-Agent': agentCreator.generateAgent()}) metatext = page.text metatext = metatext.split(' ') descripcion = [] savedescripcion = False saveimg = False og = True for texto in metatext: if '<h4>Descripción</h4>' in texto: savedescripcion = True if og and 'og:image' in texto: saveimg = True og = False if 'img/yapo' in texto: saveimg = False if savedescripcion: descripcion.append(str(texto)) if '</div>' in texto: savedescripcion = False if saveimg and 'img.yapo.cl/images' in texto: texto = texto.replace('content="', '') texto.replace('"', '') url.append(texto) if 'phone-url' in texto: texto = texto.split('"') texto = texto[1] auxPhone = texto auxPhone = 'https://www.yapo.cl' + auxPhone descripcion = descripcion[1:] first = True print(descripcion) for desc in descripcion: desc = desc.replace('\n', ' ') desc = desc.replace('<br />', '\n') desc = desc.replace('</div>', '\n') desc = desc.replace('<br>', '\n') desc = desc.replace('<br', '') desc = desc.replace('/>', '') desc = desc.replace('itemprop="description">', "") desc = desc.replace('</p>', '\n') desc = desc.replace("\t", "") desc = desc.replace('<!', '') desc = desc.replace('--', '') desc = desc.replace(' ', '') desc = desc.replace('\n', ' ') if ((len(matrixdescripcion[matrixcounter]) + len(desc)) >= 78): matrixcounter += 1 matrixdescripcion.append('') matrixdescripcion[matrixcounter] = matrixdescripcion[ matrixcounter] + str(desc) else: if first: matrixdescripcion[matrixcounter] = matrixdescripcion[ matrixcounter] + str(desc) first = False else: matrixdescripcion[matrixcounter] = matrixdescripcion[ matrixcounter] + ' ' + str(desc) print(matrixdescripcion) descripcion = '\n'.join(matrixdescripcion) propiedad.append(descripcion) try: print(auxPhone) response = requests.get( auxPhone, headers={'User-Agent': agentCreator.generateAgent()}) auxphone2 = auxPhone img = Image.open(BytesIO(response.content)) img = img.convert('L') img = img.convert('1') img.save("auxphone.gif") auxPhone = 1 except: pass lenfotos = len(url) if len(url) == 0: print("la propiedad no cuenta con fotografias") else: print('total fotos: ' + str(len(url))) for x, u in enumerate(url): u = u.replace('"', '') response = requests.get(u) img = Image.open(BytesIO(response.content)) img.save(str(x) + " foto.jpg") if not interna: imagenDescripcion = Image.new('RGB', (456, 345), color=(255, 255, 255)) d = ImageDraw.Draw(imagenDescripcion) f = ImageFont.truetype('arial.ttf', 12) d.text((0, 0), descripcion, font=f, fill=(0, 0, 0)) imagenDescripcion.save('imagenDescripcion.png') datospro = [] if pro: propsPV = reportes.from_portalinmobiliario(tipo, regionP, [comuna], "venta", True) propsYV = reportes.from_yapo(tipo, regionY, [comuna], True, "venta", True) propsV = propsPV + propsYV # aca deberiamos hacer el GB m2 = reportes.m2prom(tipo, comuna, region) m2V = m2[0] m2A = m2[1] clfHV = ensemble.GradientBoostingRegressor(n_estimators=400, max_depth=5, min_samples_split=2, learning_rate=0.1, loss='huber') #id2,fechapublicacion,fechascrap,operacion,tipo,precio,dormitorios,banos,metrosmin,metrosmax,lat,lon,estacionamientos,link preciosV = [row[5] for row in propsV] trainingV = propsV.copy() for row in trainingV: del row[13] if tipo not in ["departamento", "Casa", "Oficina"]: del row[12] del row[7] if tipo != "local": del row[6] del row[5] del row[4] del row[3] del row[2] del row[1] del row[0] x_train, x_test, y_train, y_test = train_test_split(trainingV, preciosV, test_size=0.10, random_state=2) #obtain scores venta: clfHV.fit(x_train, y_train) print("-----------") print("Score Huber:") print(clfHV.score(x_test, y_test)) scoreV = clfHV.score(x_test, y_test) clfHV.fit(trainingV, preciosV) propsPA = reportes.from_portalinmobiliario(tipo, regionP, [comuna], "arriendo", True) propsYA = reportes.from_yapo(tipo, region, [comuna], True, "arriendo", True) propsA = propsPA + propsYA # aca deberiamos hacer el GB clfHA = ensemble.GradientBoostingRegressor(n_estimators=400, max_depth=5, min_samples_split=2, learning_rate=0.1, loss='huber') #id2,fechapublicacion,fechascrap,operacion,tipo,precio,dormitorios,banos,metrosmin,metrosmax,lat,lon,estacionamientos,link preciosA = [row[5] for row in propsA] trainingA = propsA.copy() for row in trainingA: del row[13] if tipo not in ["departamento", "Casa", "Oficina"]: del row[12] del row[7] if tipo != "local": del row[6] del row[5] del row[4] del row[3] del row[2] del row[1] del row[0] x_train, x_test, y_train, y_test = train_test_split(trainingA, preciosA, test_size=0.10, random_state=2) #obtain scores arriendo: clfHA.fit(x_train, y_train) print("-----------") print("Score Huber:") print(clfHA.score(x_test, y_test)) scoreA = clfHA.score(x_test, y_test) clfHA.fit(trainingA, preciosA) textmail += "Resultados comuna " + str( comuna) + ":\n" + "Score Ventas: " + str( (int(10000 * scoreV)) / 100) + "%\nScore Arriendos: " + str( (int(10000 * scoreA)) / 100) + "%\nPrecio m2 Venta: UF." + str( (int(10 * (m2V / ufn))) / 10) + "\nPrecio m2 Arriendo: $" + str( (int(m2A))) + "\n\n" if tipo not in ["departamento", "Casa", "Oficina"]: prop = [banos, metrosmin, metrosmax, lat, lon] if tipo != "local": prop = [metrosmin, metrosmax, lat, lon] else: prop = [ dormitorios, banos, metrosmin, metrosmax, lat, lon, estacionamientos ] tasacionVenta = clfHV.predict([prop]) tasacionArriendo = clfHA.predict([prop]) precioV = tasacionVenta precioA = tasacionArriendo print("el precio tasado de venta inicial es: " + str(precioV)) print("el precio tasado de arriendo inicial es: " + str(precioA)) if operacion == 'venta': if precioV is None or precioV < 0.1: pro = False financiera = False try: rentaV = ((precioV - precio) / precio) except: pro = False financiera = False text2 = 'No se ha podido realizar tasación' print('fail 1') if precioA is None or precioA < 0.01: pro = False financiera = False try: rentaA = (precioA * 12 / precio) except: pro = False financiera = False text2 = 'No se ha podido realizar tasación' print('fail 2') if pro: if rentaA > 0.2: pro = False financiera = False print('fail 3') if rentaA < 0: pro = False financiera = False if pro: # precio venta tasado datospro.append(precioV) # rentabilidad de venta datospro.append(float(rentaV)) # precio arriendo tasado datospro.append(precioA) # rentabilidad de arriendo datospro.append(float(rentaA)) else: try: precioA = tasacionArriendo except: pro = False text2 = 'No se ha podido realizar tasación' print('fail 72') if pro: if precioA is None or precioA < 0.01: pro = False text2 = 'No se ha podido realizar tasación' print('fail 8') if pro: # precio arriendo tasado datospro.append(precioA) # rentabilidad de arriendo datoscontacto = [] if interna: if sitio == 'portal': try: email, telefono, dueno = reportes.getDatosDueno(str(id)) except: email = "NN" telefono = "NN" dueno = "NN" else: email = "NN" if auxPhone == 1: telefono = auxphone2 else: telefono = "NN" dueno = 'NN' datoscontacto.append(email) datoscontacto.append(telefono) datoscontacto.append(dueno) #Crear PDF if interna: nombrearchivo = "Ficha Propiedad Sitio:" + str(sitio) + " Id:" + str( id) + ".pdf" else: nombrearchivo = "Ficha Propiedad Sitio:" + str(sitio) + ", " + str( operacion) + ", " + str(tipo) + ", " + str(region) + ", " + str( comuna) + ".pdf" print(nombrearchivo) links = [] if financiera: pro = "financiera" print("entering pdfCreator") pdfCreatorFichas.crearPdfFicha(nombrearchivo, id, propiedad, lenfotos, pro, datospro, interna, datoscontacto, regionP, links) print("pdf generado con exito") #Enviar PDF sendmail.sendMail(mail, "", nombrearchivo) #Eliminar del servidor if len(url) == 0: pass else: for x, u in enumerate(url): os.remove(str(x) + " foto.jpg") try: os.remove("auxphone.gif") except: pass if not interna: try: os.remove("imagenDescripcion.png") except: pass os.remove(nombrearchivo) #Retornar exito text = "Ficha creada para la propiedad: " + str( id) + " obtenida del sitio: " + str( sitio) + ", enviada con éxito al correo: " + str(mail) + "." if text2 != '': text = text2 + '. ' + text return (text)
def obtainPropFromYapo(link): codigo = -1 idregion = -1 comuna = "" tipo = "" titulo = "" operacion = "" preciouf = -1 preciopesos = -1 fechapublicacion = "" fechahoy = datetime.datetime.now() fechascrap = str(fechahoy.year) + '-' + str(fechahoy.month) + '-' + str( fechahoy.day) metrosmin = -1 metrosmax = -1 dormitorios = -1 banos = -1 descripcion = "" lat = -999 lon = -999 anoconstruccion = -1 ggcc = -1 estacionamientos = 0 esdueno = 0 page = requests.get(link, headers={'User-Agent': agentCreator.generateAgent()}) tree = html.fromstring(page.content) url = [] metatext = page.text metatext = metatext.split(' ') descripcion = [] savedescripcion = False saveimg = False og = True telefono = 'NN' precio1 = tree.xpath( '//*[@id="content"]/section[1]/article/div[5]/div[1]/table/tbody/tr[1]/td/div/strong' ) precio2 = tree.xpath( '//*[@id="content"]/section[1]/article/div[5]/div[1]/table/tbody/tr[1]/td/div/span/span' ) '//*[@id="content"]/section[1]/article/div[5]/div[1]/table/tbody/tr[1]/td/div/strong' '//*[@id="content"]/section[1]/article/div[5]/div[1]/table/tbody/tr[1]/td/div/span/span' if len(precio1) < 0: return False if len(precio2) == 0: print("Error al sacar el precio en " + link) return False if ('$') in precio2[0].text: preciopesos = precio2[0].text preciouf = precio1[0].text else: preciopesos = precio1[0].text preciouf = precio2[0].text preciopesos = preciopesos.replace('.', '') preciopesos = preciopesos.replace('$', '') preciopesos = preciopesos.replace(' ', '') preciopesos = preciopesos.replace(')', '') preciopesos = preciopesos.replace('(', '') preciopesos = preciopesos.replace('*', '') preciopesos = int(preciopesos) preciouf = preciouf.replace('.', '') preciouf = preciouf.replace('$', '') preciouf = preciouf.replace(' ', '') preciouf = preciouf.replace(')', '') preciouf = preciouf.replace('(', '') preciouf = preciouf.replace('*', '') preciouf = preciouf.replace('UF', '') preciouf = preciouf.replace(',', '.') preciouf = float(preciouf) #extraccion codigo aux = link.split('.') aux = aux[-2] aux = aux.split('_') codigo = int(aux[-1]) utag_data = tree.xpath("/html/body/script[1]/text()")[0] text = str(utag_data.split('=')[1]) text = text[:-5] + "}" try: value = json.loads(text) except: return False try: idregion = value["region_level2_id"].lower() except: pass try: comuna = value["region_level3"].lower() except: pass try: titulo = value["ad_title"].lower() except: pass try: if value["category_level2"] == "Vendo": operacion = "venta" elif value["category_level2"] == "Arriendo": operacion = "arriendo" elif value["category_level2"] == "Arriendo de temporada": operacion = "temporada" except: pass try: fechapublicacion = value["publish_date"].split(' ')[0] except: pass try: dormitorios = int(value["rooms"]) except: pass try: descripcion = value["description"] except: pass try: if int(value["geoposition_is_precise"]) == 1: pos = value["geoposition"].split(',') lat = float(pos[0]) lon = float(pos[1]) except: pass tabla = tree.xpath( """//*[@id="content"]/section[1]/article/div[5]/div[1]/table/tbody/tr""" ) tabla.pop(0) for row in tabla: rowname = row.find("th").text if rowname == "Tipo de inmueble": tipo = row.find("td").text elif rowname == "Superficie total": metrosmax = row.find("td").text.replace('\n', '').replace( '\t', '').split(' ')[0] elif rowname == "Superficie útil" or rowname == "Superficie construida": metrosmin = row.find("td").text.replace('\n', '').replace( '\t', '').split(' ')[0] elif rowname == "Baños": banos = row.find("td").text banos = int(str(banos.split(' ')[0])) elif rowname == "Estacionamiento": estacionamientos = row.find("td").text elif rowname == "Año de construcción": anoconstruccion = row.find("td").text elif rowname == "Gastos comunes": ggcc = row.find("td").text[2:] ggcc = ggcc.replace('.', '') ggcc = float(ggcc) try: propiedad = [] propiedad.append(titulo) propiedad.append(idregion) propiedad.append(operacion.lower()) propiedad.append(tipo.lower()) propiedad.append(preciopesos) propiedad.append(int(float(dormitorios))) propiedad.append(int(float(banos))) propiedad.append(int(float(metrosmin))) propiedad.append(int(float(metrosmax))) propiedad.append(int(float(estacionamientos))) propiedad.append(int(float(estacionamientos))) propiedad.append(lat) propiedad.append(lon) propiedad.append(link) propiedad.append(comuna) return propiedad except Exception as err: print("Error en propiedad:" + link + " \n " + str(err)) return False