1

Que tal retomando un proyecto en python utilizando selenium, y BeautifulSoup una ves hago correr me sale el mensaje "could not convert string to float: ''", cuando imprimo lat y lng, pero cuando imprimo la variable coor que es donde están los datos que quiero extraer imprime todo el texto completo, los valores que intento extraer son coordenadas.

import requests
from bs4 import BeautifulSoup
import pygame
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options

pygame.init()
num = 1
n = 1
for i in range(1, 21):

    num += 1

    chrome_options = Options()

    chrome_options .add_argument(
    "user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/71.0.3578.80 Chrome/71.0.3578.80 Safari/537.36"
    )

    driver = webdriver.Chrome('./chromedriver.exe', 
    chrome_options=chrome_options)

    url = driver.get(
         'https://www.infocasas.com.bo/venta/casas-y-departamentos-y-lotes-o- 
    terrenos-y-locales-comerciales-y-oficinas/cochabamba/pagina' + str(num))
    sleep(10)
    links_productos = driver.find_elements(By.XPATH, '//div[@class="ant-card-body"]/a')

    links_de_la_pagina = []

    for tag_a in links_productos:
        links_de_la_pagina.append(tag_a.get_attribute("href"))

    for link in links_de_la_pagina:
        try:
            driver.get(link)
            sleep(8)

            page = requests.get(link)
            soup = BeautifulSoup(page.content, 'html.parser')
            coor = soup.find('script', type="application/json")

            print(coor)
            ini_lat = coor.text.find("latitude") + 2
            ini_lng = coor.text.find("longitude") + 2

            lat = coor.text[ini_lat: ini_lat + 15]
            lng = coor.text[ini_lng: ini_lng + 15]
            lat = float(lat)
            lng = float(lng)
            print(lat)
            print(lng)
            print('\n')


            driver.back()
        except Exception as e:
            print(e)
            driver.back()
        n += 1

Adjunto el valor de la variable coor el cual cuando imprimo muestra el valor completo.

<script id="__NEXT_DATA__" type="application/json">{"props":{"pageProps":{"__PROPERTY__ID__":186033468,"UrlToBack":-1,"DummyContextInitialState":{"count":23},"apolloState":{"Currency:1":{"id":"1","__typename":"Currency","name":"U$S"},"HeaderLink:17":{"id":"17","__typename":"HeaderLink","title":"Venta","link":"https://www.infocasas.com.bo/venta/inmuebles/santa-cruz","banner_params":null,"links":[]},"HeaderLink:18":{"id":"18","__typename":"HeaderLink","title":"Alquiler","link":"https://www.infocasas.com.bo/alquiler/inmuebles/santa-cruz","banner_params":null,"links":[]},"HeaderLink:19":{"id":"19","__typename":"HeaderLink","title":"Anticrético","link":"https://www.infocasas.com.bo/anticretico/inmuebles/santa-cruz","banner_params":null,"links":[]},"HeaderLink:20":{"id":"20","__typename":"HeaderLink","title":"Proyectos","link":"https://www.infocasas.com.bo/proyectos","banner_params":null,"links":[]},"ROOT_QUERY":{"__typename":"Query","configuration":{"__typename":"CountryConfiguration","country_id":"5","country_name":"Bolivia","country_capital":"Santa Cruz","country_capital_id":157,"country_code":"bo","site_name":"InfoCasas","logo":"https://cdn2.infocasas.com.uy/web/[email protected]","information_email":"[email protected]","sales_email":"[email protected]","main_domain":"www.infocasas.com.bo","phone":"(+591) 75 007 272","currency":{"__ref":"Currency:1"},"timezone":"America/La_Paz","IVA":0.1494,"analytics_id":"UA-42476608-8","google_tag_manager_id":"GTM-K45BKDG","rtb_id":null,"onesignal_configuration":{"__typename":"OneSignalConfiguration","app_id":"b54776ca-b617-4a52-8537-7e271bc6f1b3"},"facebook_configuration":{"__typename":"FacebookConfiguration","pixel_id":"1356516007721063"},"pinterest_id":"3ea07d0b3cfc471393127fbac3c1982c","instagram_client_id":"1468183759919462","header_configuration":{"__typename":"HeaderConfiguration","buttons":[]},"socialMediaLinks":[{"__typename":"SocialMediaLinks","slug":"InfoCasasBO","name":"Twitter","url":"https://twitter.com/infocasasbo","icon":"icon-twitter"},{"__typename":"SocialMediaLinks","slug":"InfoCasas","name":"LinkedIn","url":"https://www.linkedin.com/company/infocasasbolivia","icon":"icon-linkedin"},{"__typename":"SocialMediaLinks","slug":"InfoCasas","name":"YouTube","url":"https://www.youtube.com/channel/UC4E8K3kQ4jL-0mVh6fbAzeA","icon":"icon-youtube"},{"__typename":"SocialMediaLinks","slug":"InfoCasasBO","name":"Instagram","url":"https://www.instagram.com/infocasasbo/","icon":"icon-instagram"},{"__typename":"SocialMediaLinks","slug":"InfoCasasBO","name":"Facebook","url":"https://www.facebook.com/infocasas.bo/","icon":"icon-facebook-1"}],"header_links":[{"__ref":"HeaderLink:17"},{"__ref":"HeaderLink:18"},{"__ref":"HeaderLink:19"},{"__ref":"HeaderLink:20"}]},"seoMetaTags({\"url\":\"/tu-nuevo-hogar-casa-5-dormitorios/186033468\"})":{"__typename":"SeoMetaTags","h1":"TU NUEVO HOGAR CASA 5 Dormitorios","title":"TU NUEVO HOGAR CASA 5 Dormitorios. Ref #62E2A - infocasas.com.bo","breadcrumbs":[{"__typename":"BreadCrumb","text":"InfoCasas","url":"/"},{"__typename":"BreadCrumb","text":"Venta","url":"/venta"},{"__typename":"BreadCrumb","text":"Casas","url":"/venta/casas"},{"__typename":"BreadCrumb","text":"Cochabamba","url":"/venta/casas/cochabamba"},{"__typename":"BreadCrumb","text":"Tiquipaya","url":"/venta/casas/cochabamba/tiquipaya"},{"__typename":"BreadCrumb","text":"TU NUEVO HOGAR CASA 5 Dormitorios","url":"/tu-nuevo-hogar-casa-5-dormitorios/186033468"}],"url":"https://www.infocasas.com.bo/tu-nuevo-hogar-casa-5-dormitorios/186033468","description":"\u003cp\u003e$US155.000 REMATO CASA!\u003c/p\u003e\u003cp\u003eEn Condominio PRIVADO\u003c/p\u003e\u003cp\u003e1er Piso: Living, comedor, cocina, despensa, baño visitas, patio\u003c/p\u003e\u003cp\u003e2do Piso:1 dormitorio en sui.... Ref #62E2A - .infocasas.com.bo","og_image":"https://cdn1.infocasas.com.uy/repo/img/7732f90c61f829079415d24ae438d375ab855cbe.jpg#HASTH","noindex":false,"canonical":"https://www.infocasas.com.bo/tu-nuevo-hogar-casa-5-dormitorios/186033468","site_name":"InfoCasas","links":null,"text":"TU NUEVO HOGAR CASA 5 Dormitorios es una Casa de 5 dormitorios, 3 baños y 234 m2 construida en 2013. Tiquipaya Condominio Acasias Se ubica en Tiquipaya, Cochabamba. Esta propiedad se encuentra disponible a la venta y fue ingresada por Eeva Alejandra Ede el 24 de abril de 2019. El precio de Venta es de U$S 155.000","seoLanding":null},"property({\"id\":186033468})":{"__ref":"Property:186033468"},"bigData({\"getFirst\":1,\"params\":{\"page\":1,\"property_id\":\"\"}})":[],"bigData({\"getFirst\":1,\"params\":{\"page\":1,\"property_id\":\"186033468\"}})":null},"Individual:417713":{"id":"417713","__typename":"Individual","name":"Eeva Alejandra Ede","masked_phone":"76750","has_whatsapp":true,"logo":"https://lh3.googleusercontent.com/a-/AAuE7mCZIpV2vcHD0oEMlVCpiCTdxov4Ld9449MaCZlb?sz=200","inmoLink":null,"inmoPropsLink":"/inmobiliarias/417713-eeva-alejandra-ede/propiedades","inmofull":false,"type":null},"Estate:161":{"id":"161","__typename":"Estate","name":"Cochabamba"},"Neighborhood:2415":{"id":"2415","__typename":"Neighborhood","name":"Tiquipaya","estate":{"__ref":"Estate:161"},"lat":null,"long":null},"PropertyType:1":{"id":"1","__typename":"PropertyType","name":"Casa"},"OperationType:1":{"id":"1","__typename":"OperationType","name":"Venta"},"PropertyFacility:1":{"id":"1","__typename":"PropertyFacility","name":"Balcón","group":"Confort del apartamento"},"PropertyFacility:2":{"id":"2","__typename":"PropertyFacility","name":"Box","group":"Confort del apartamento"},"PropertyFacility:4":{"id":"4","__typename":"PropertyFacility","name":"Calefón","group":"Confort del apartamento"},"PropertyFacility:6":{"id":"6","__typename":"PropertyFacility","name":"Depósito","group":"Confort del apartamento"},"PropertyFacility:7":{"id":"7","__typename":"PropertyFacility","name":"Dormitorio de servicio","group":"Confort del apartamento"},"PropertyFacility:9":{"id":"9","__typename":"PropertyFacility","name":"Garaje","group":"Confort del apartamento"},"PropertyFacility:13":{"id":"13","__typename":"PropertyFacility","name":"Parrillero","group":"Confort del apartamento"},"PropertyFacility:14":{"id":"14","__typename":"PropertyFacility","name":"Placard en cocina","group":"Confort del apartamento"},"PropertyFacility:15":{"id":"15","__typename":"PropertyFacility","name":"Placard en dormitorio","group":"Confort del apartamento"},"PropertyFacility:18":{"id":"18","__typename":"PropertyFacility","name":"Vestidor","group":"Confort del apartamento"},"PropertyFacility:25":{"id":"25","__typename":"PropertyFacility","name":"Lavandería","group":"Confort del edificio"},"PropertyFacility:27":{"id":"27","__typename":"PropertyFacility","name":"Piscina","group":"Confort del edificio"},"PropertyFacility:37":{"id":"37","__typename":"PropertyFacility","name":"Gas por Cañería","group":"Instalaciones apartamento"},"PropertyFacility:70":{"id":"70","__typename":"PropertyFacility","name":"Jardín","group":"Confort de la casa"},"PropertyFacility:72":{"id":"72","__typename":"PropertyFacility","name":"Patio","group":"Confort de la casa"},"PropertyFacility:216":{"id":"216","__typename":"PropertyFacility","name":"Walk-in Closet","group":"Confort de la casa"},"PropertyFacility:218":{"id":"218","__typename":"PropertyFacility","name":"Living comedor","group":"Confort de la casa"},"Image:35161501":{"id":"35161501","__typename":"Image","image":"https://cdn1.infocasas.com.uy/repo/img/7732f90c61f829079415d24ae438d375ab855cbe.jpg","tag":""},"Image:35161489":{"id":"35161489","__typename":"Image","image":"https://cdn1.infocasas.com.uy/repo/img/eab3e26ba1c9764bb45f6485a84e6129c71dbd3a.jpg","tag":""},"Image:35161490":{"id":"35161490","__typename":"Image","image":"https://cdn1.infocasas.com.uy/repo/img/45b02b94e78f22c891c76b7b40e5e3d2b2735220.jpg","tag":""},"Image:35161491":{"id":"35161491","__typename":"Image","image":"https://cdn1.infocasas.com.uy/repo/img/fc329fb811f31f8c10e351516571059a2aac60bd.jpg","tag":""},"Image:35161492":{"id":"35161492","__typename":"Image","image":"https://cdn1.infocasas.com.uy/repo/img/5c4be6e42d002cce3515e18f19ca467fa8a318b2.jpg","tag":""},"Image:38425285":{"id":"38425285","__typename":"Image","image":"https://cdn1.infocasas.com.uy/repo/img/28ffbc504569d59b8c8702b7276437e328085093.jpeg","tag":""},"Image:35161495":{"id":"35161495","__typename":"Image","image":"https://cdn1.infocasas.com.uy/repo/img/73eac4040443db09e240c89ecaaac77bdb535d5c.jpg","tag":""},"Image:35161497":{"id":"35161497","__typename":"Image","image":"https://cdn1.infocasas.com.uy/repo/img/0adcfb89932ce84ee1bb17c05d8b59c9ec910178.jpg","tag":""},"Image:35161498":{"id":"35161498","__typename":"Image","image":"https://cdn1.infocasas.com.uy/repo/img/13ba9ccbbaeca215cc2119bc86ed251fb2430cd0.jpg","tag":""},"Image:35161499":{"id":"35161499","__typename":"Image","image":"https://cdn1.infocasas.com.uy/repo/img/b243e375a5fc237e0063c127cc1ed82e1021f1e2.jpg","tag":""},"Image:35161500":{"id":"35161500","__typename":"Image","image":"https://cdn1.infocasas.com.uy/repo/img/3bdf68696170e97449695b2015a86e7957bebce5.jpg","tag":""},"Image:38425276":{"id":"38425276","__typename":"Image","image":"https://cdn1.infocasas.com.uy/repo/img/8eb78fd5ab8bb695dffc66f49618fd7617a20eae.jpg","tag":""},"Image:35161493":{"id":"35161493","__typename":"Image","image":"https://cdn1.infocasas.com.uy/repo/img/12d0c1f82dd03ec5b2e7b3dfefc118227d858f46.jpg","tag":""},"Image:35161494":{"id":"35161494","__typename":"Image","image":"https://cdn1.infocasas.com.uy/repo/img/cfeccfc4434838abc3619e8c96a2577a41430502.jpg","tag":""},"Image:38425272":{"id":"38425272","__typename":"Image","image":"https://cdn1.infocasas.com.uy/repo/img/186af98548dabaacf44b662da12260bc190ebf95.jpg","tag":""},"Image:38425280":{"id":"38425280","__typename":"Image","image":"https://cdn1.infocasas.com.uy/repo/img/ad666cb51c4b8ad5ca3ca0ae06661da48e222b39.jpg","tag":""},"Property:186033468":{"id":"186033468","__typename":"Property","title":"TU NUEVO HOGAR CASA 5 Dormitorios","typeID":1,"address":"Tiquipaya Condominio Acasias","showAddress":true,"country_id":5,"description":"\u003cp\u003e$US155.000 REMATO CASA!\u003c/p\u003e\u003cp\u003eEn Condominio PRIVADO\u003c/p\u003e\u003cp\u003e1er Piso: Living, comedor, cocina, despensa, baño visitas, patio\u003c/p\u003e\u003cp\u003e2do Piso:1 dormitorio en suite (con baño privado y walking closet), sala de estar, 2 dormitorios con baño compartido.\u003c/p\u003e\u003cp\u003e3er Piso: 2 dormitorios con baño compartido\u003c/p\u003e\u003cp\u003eExterior: Lavandería, dependencia de empleada (con baño propio), parrillero, jardín y patio trasero.\u003c/p\u003e\u003cp\u003eIncluye: Muebles de cocina, box de baños, roperos y cortinas.\u003c/p\u003e\u003cp\u003eÁreas compartidas: Piscina de adultos y niños.\u003c/p\u003e\u003cp\u003e314m2 terreno 234m2 construido\u003c/p\u003e\u003cp\u003e\u003cbr\u003e\u003c/p\u003e","code":"62E2A","code2":null,"finances":true,"grouped_ids":null,"img":"https://cdn1.infocasas.com.uy/repo/img/7732f90c61f829079415d24ae438d375ab855cbe.jpg#HASTH","price":{"__typename":"Price","amount":155000,"currency":{"__typename":"Currency","name":"U$S","rate":1},"hidePrice":false},"price_amount_usd":155000,"owner":{"__ref":"Individual:417713"},"neighborhood":{"__ref":"Neighborhood:2415"},"estate":{"__ref":"Estate:161"},"seller":null,"technicalSheet":[{"__typename":"TechnicalSheet","field":"code","value":"62E2A","text":"Referencia"},{"__typename":"TechnicalSheet","field":"property_type_name","value":"Casa","text":"Tipo de Propiedad"},{"__typename":"TechnicalSheet","field":"neighborhood_name","value":"Tiquipaya","text":"Zona"},{"__typename":"TechnicalSheet","field":"construction_state_name","value":"Buen estado","text":"Estado"},{"__typename":"TechnicalSheet","field":"disposition_name","value":"No aplica","text":"Disposición"},{"__typename":"TechnicalSheet","field":"bathrooms","value":"3","text":"Baños"},{"__typename":"TechnicalSheet","field":"m2Built","value":"234 m2","text":"M² edificados"},{"__typename":"TechnicalSheet","field":"m2Terrace","value":null,"text":"M² de terraza"},{"__typename":"TechnicalSheet","field":"m2Terrain","value":"314 m2","text":"M² del terreno"},{"__typename":"TechnicalSheet","field":"brightness","value":null,"text":"Luminosidad"},{"__typename":"TechnicalSheet","field":"constructionYear","value":"2013","text":"Año de Construcción"},{"__typename":"TechnicalSheet","field":"floor","value":null,"text":"Piso"},{"__typename":"TechnicalSheet","field":"bedrooms","value":"5","text":"Dormitorios"},{"__typename":"TechnicalSheet","field":"sea_distance_name","value":null,"text":"Distancia al Mar"},{"__typename":"TechnicalSheet","field":"seaview","value":null,"text":"Vista al Mar"},{"__typename":"TechnicalSheet","field":"address","value":"Tiquipaya Condominio Acasias","text":"Dirección"},{"__typename":"TechnicalSheet","field":"garage","value":"1","text":"Garajes"},{"__typename":"TechnicalSheet","field":"story","value":"3","text":"Plantas"},{"__typename":"TechnicalSheet","field":"floorsAmount","value":null,"text":"Cantidad de Pisos"},{"__typename":"TechnicalSheet","field":"over_name","value":"No aplica","text":"Sobre"},{"__typename":"TechnicalSheet","field":"occupancyExpenses","value":null,"text":"Gastos de ocupación"},{"__typename":"TechnicalSheet","field":"initialFee","value":null,"text":"Cuota inicial"},{"__typename":"TechnicalSheet","field":"socialHousing","value":"Si","text":"Vivienda Social"},{"__typename":"TechnicalSheet","field":"barter","value":null,"text":"Acepta permuta"}],"image_count":16,"file_count":0,"imgSize":50693,"link":"tu-nuevo-hogar-casa-5-dormitorios/186033468","property_type":{"__ref":"PropertyType:1"},"operation_type":{"__ref":"OperationType:1"},"barter":false,"facilities":[{"__ref":"PropertyFacility:1"},{"__ref":"PropertyFacility:2"},{"__ref":"PropertyFacility:4"},{"__ref":"PropertyFacility:6"},{"__ref":"PropertyFacility:7"},{"__ref":"PropertyFacility:9"},{"__ref":"PropertyFacility:13"},{"__ref":"PropertyFacility:14"},{"__ref":"PropertyFacility:15"},{"__ref":"PropertyFacility:18"},{"__ref":"PropertyFacility:25"},{"__ref":"PropertyFacility:27"},{"__ref":"PropertyFacility:37"},{"__ref":"PropertyFacility:70"},{"__ref":"PropertyFacility:72"},{"__ref":"PropertyFacility:216"},{"__ref":"PropertyFacility:218"}],"m2":234,"hectares":0,"created_at":"2019-04-24","updated_at":"2020-10-07","latitude":-17.355236369496644,"images":[{"__ref":"Image:35161501"},{"__ref":"Image:35161489"},{"__ref":"Image:35161490"},{"__ref":"Image:35161491"},{"__ref":"Image:35161492"},{"__ref":"Image:38425285"},{"__ref":"Image:35161495"},{"__ref":"Image:35161497"},{"__ref":"Image:35161498"},{"__ref":"Image:35161499"},{"__ref":"Image:35161500"},{"__ref":"Image:38425276"},{"__ref":"Image:35161493"},{"__ref":"Image:35161494"},{"__ref":"Image:38425272"},{"__ref":"Image:38425280"}],"files":[],"source":0,"project":[],"color":3,"longitude":-66.19868874549866,"pausd":false,"pointType":false,"zoom":15,"youtube":null,"highlight":7,"active":true,"deleted":false,"relevance":91.9061,"construction_year":"2013","notes":"","sold":false,"soldDate":"0000-00-00","discount":null,"draft":false,"sign":null,"guarantee":"","facilitiesNotApply":false,"commonExpenses":null,"price_variation":null,"ceCurrencyID":null,"highlightDate":"2019-06-11","socialMediaLinks":[{"__typename":"SocialMediaLinks","slug":"twitter","name":"twitter","url":"https://twitter.com/intent/tweet?url=https://www.infocasas.com.bo/tu-nuevo-hogar-casa-5-dormitorios/186033468","icon":"icon-twitter","order":null},{"__typename":"SocialMediaLinks","slug":"linkedin","name":"linkedin","url":"https://www.linkedin.com/shareArticle?mini=true\u0026url=https://www.infocasas.com.bo/tu-nuevo-hogar-casa-5-dormitorios/186033468","icon":"icon-linkedin","order":null},{"__typename":"SocialMediaLinks","slug":"facebook","name":"facebook","url":"https://www.facebook.com/sharer/sharer.php?u=https://www.infocasas.com.bo/tu-nuevo-hogar-casa-5-dormitorios/186033468","icon":"icon-facebook-1","order":null},{"__typename":"SocialMediaLinks","slug":"email","name":"email","url":"mailto:?subject=PropiedadRecomendada-InfoCasas\u0026body=LinkdelaPropiedad:https://www.infocasas.com.bo/tu-nuevo-hogar-casa-5-dormitorios/186033468","icon":"icon-mail","order":null}],"m2Built":234,"garage":true,"office":false,"dispositionID":1,"bathrooms":3,"bedrooms":5,"rooms":6,"seaDistanceID":null,"seaview":false,"livingPlace":true,"condominium":true,"frontLength":"","floorsCount":0,"m2apto":0,"apartmentsPerFloor":0,"floor":null,"neighborhood_id":2415,"estate_id":161,"farmhouse":false,"allowedHeight":"","isFavorite":null,"isExternal":false,"guests":null,"seasons":[],"occupancies":[],"temporal_price":null,"temporal_currency":null}},"ConfigContextInitialState":{"__typename":"CountryConfiguration","country_id":"5","country_name":"Bolivia","country_capital":"Santa Cruz","country_capital_id":157,"country_code":"bo","site_name":"InfoCasas","logo":"https://cdn2.infocasas.com.uy/web/[email protected]","information_email":"[email protected]","sales_email":"[email protected]","main_domain":"www.infocasas.com.bo","phone":"(+591) 75 007 272","currency":{"__typename":"Currency","id":"1","name":"U$S"},"timezone":"America/La_Paz","IVA":0.1494,"analytics_id":"UA-42476608-8","google_tag_manager_id":"GTM-K45BKDG","rtb_id":null,"onesignal_configuration":{"__typename":"OneSignalConfiguration","app_id":"b54776ca-b617-4a52-8537-7e271bc6f1b3"},"facebook_configuration":{"__typename":"FacebookConfiguration","pixel_id":"1356516007721063"},"pinterest_id":"3ea07d0b3cfc471393127fbac3c1982c","instagram_client_id":"1468183759919462","header_configuration":{"__typename":"HeaderConfiguration","buttons":[]},"socialMediaLinks":[{"__typename":"SocialMediaLinks","slug":"InfoCasasBO","name":"Twitter","url":"https://twitter.com/infocasasbo","icon":"icon-twitter"},{"__typename":"SocialMediaLinks","slug":"InfoCasas","name":"LinkedIn","url":"https://www.linkedin.com/company/infocasasbolivia","icon":"icon-linkedin"},{"__typename":"SocialMediaLinks","slug":"InfoCasas","name":"YouTube","url":"https://www.youtube.com/channel/UC4E8K3kQ4jL-0mVh6fbAzeA","icon":"icon-youtube"},{"__typename":"SocialMediaLinks","slug":"InfoCasasBO","name":"Instagram","url":"https://www.instagram.com/infocasasbo/","icon":"icon-instagram"},{"__typename":"SocialMediaLinks","slug":"InfoCasasBO","name":"Facebook","url":"https://www.facebook.com/infocasas.bo/","icon":"icon-facebook-1"}],"header_links":[{"__typename":"HeaderLink","id":"17","title":"Venta","link":"https://www.infocasas.com.bo/venta/inmuebles/santa-cruz","banner_params":null,"links":[]},{"__typename":"HeaderLink","id":"18","title":"Alquiler","link":"https://www.infocasas.com.bo/alquiler/inmuebles/santa-cruz","banner_params":null,"links":[]},{"__typename":"HeaderLink","id":"19","title":"Anticrético","link":"https://www.infocasas.com.bo/anticretico/inmuebles/santa-cruz","banner_params":null,"links":[]},{"__typename":"HeaderLink","id":"20","title":"Proyectos","link":"https://www.infocasas.com.bo/proyectos","banner_params":null,"links":[]}]},"country_id":"5","statusCode":200}},"page":"/propSingle","query":{"hashed":"eyJpZCI6MTg2MDMzNDY4fQ=="},"buildId":"HIZ-4YWwugihX53qXnopI","assetPrefix":"https://cdn2.infocasas.com.uy/frontend","runtimeConfig":{"NODE_ENV":"production","sentryDNS":"https://[email protected]/2679673","googleClientID":"294615345597-9ghmg15vcsfar1b1sqvcqphukull84gn.apps.googleusercontent.com","facebookAppID":"1402860790042682","googleMapsApiKey":"AIzaSyDBA9FLlSyCGsbvPX-IGZm5BdAFnM04zUw","logrocketID":"lkvvhi/infocasas","ybugID":"wxrjbv9hyndrbqd1tq3m","APP_NAME":"infonext","APP_VERSION":"2.4.0"},"isFallback":false,"customServer":true,"gip":true}</script>

Agradecería mucho un poco de ayuda.

3
  • Hay una mala indentación en el primer for y lo que va dentro. Arregla bien el código para poder reproducir el problema.
    – aeportugal
    Commented el 30 mar. 2021 a las 19:57
  • Puedes mostrar también lo que contiene la variable coor.text? Posiblemente el problema se pueda resolver simplemente conociendo ese dato, y así nos evitamos tener que instalar selenium y sus drivers sólo para reproducir el problema
    – abulafia
    Commented el 30 mar. 2021 a las 20:09
  • @abulafia Ya edite la pregunta mostrando el contenido de la variable coor, gracias por la ayuda
    – DAVE
    Commented el 31 mar. 2021 a las 13:05

2 respuestas 2

0

La instrucción coor = soup.find('script', type="application/json") devuelve un string en formato JSON, se puede parsear y tratar como tal.

Colocar esto en el encabezado del script:

import json

Ahora dentro del bloque try:

# ...
driver.get(link)
sleep(8)

page = requests.get(link)
soup = BeautifulSoup(page.content, 'html.parser')
coor = soup.find('script', type="application/json") # <-- string JSON
            
json_object = json.loads(coor.contents[0]) # <-- Parse JSON (ver link referencia)

prop_id = json_object["props"]["pageProps"]["__PROPERTY__ID__"]
ini_lat = json_object["props"]["pageProps"]["apolloState"][f"Property:{prop_id}"]["latitude"]
ini_lng = json_object["props"]["pageProps"]["apolloState"][f"Property:{prop_id}"]["longitude"]
            
print(ini_lat)
print(ini_lng)
# ...

Referencia (en inglés) How to extract json from script tag using beautiful soup

[!] Notas. Este script se puede mejorar, por ejemplo, no veo un motivo por el cual el driver se tenga que definir 20 veces en el primer for, esa parte puede quedar fuera. Y no estaría mal echarle una ojeada a DriverWait y ExpectedConditions para hacer esperas más precisas e inteligentes.

0

Muchas gracias por la ayuda reviso los links para mas información así poder afinar la extracción de datos, haciendo una profunda revisión al fin logre resolverlo, al final el código quedo así (por si a alguien le sirve):

import requests
from bs4 import BeautifulSoup
import pygame
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options

pygame.init()
num = 1
n = 1
for i in range(1, 21):
    num += 1
    chrome_options = Options()

    chrome_options.add_argument(
    "user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/71.0.3578.80 Chrome/71.0.3578.80 Safari/537.36"
    )

    driver = webdriver.Chrome('./chromedriver.exe', chrome_options=chrome_options)

    url = driver.get(
    'https://www.infocasas.com.bo/venta/casas-y-departamentos-y-lotes-o-terrenos-y-locales-comerciales-y-oficinas/cochabamba/pagina' + str(num))
    sleep(10)
    links_productos = driver.find_elements(By.XPATH, '//div[@class="ant-card-body"]/a')

    links_de_la_pagina = []

    for tag_a in links_productos:
        links_de_la_pagina.append(tag_a.get_attribute("href"))

    for link in links_de_la_pagina:
        try:
            driver.get(link)
            sleep(8)

            page = requests.get(link)
            soup = BeautifulSoup(page.content, 'html.parser')
            coor = soup.find('script', type="application/json")
            print(coor)
            ini_lat = coor.string.find('"latitude":') + 11
            ini_lng = coor.string.find('"longitude":') + 12
            lat = coor.string[ini_lat: ini_lat + 10]
            lng = coor.string[ini_lng: ini_lng + 10]
            lat = float(lat)
            lng = float(lng)
            print(lat)
            print(lng)
            print('\n')

            driver.back()
        except Exception as e:
            print(e)
            driver.back()
        n += 1

Respondiendo si bien el primer for tienen como rango 21 es por la paginación ya que el script hace un recorrido por pagina entrando un enlace a la vez. Gracias por la ayuda me sirvió mucho.

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.