I am getting the error when I try to run the following code. I know it has something to do with the formating of the json file but I am not sure how to proceed/change in order to be able to get floats from the json file
print(location['latitude']) TypeError: string indices must be integers
my code
import requests import bs4 as bs import urllib.parse import json from datetime import datetime, timedelta import time import re url='https://www.vrbo.com/el-gr/%CE%B5%CE%BD%CE%BF%CE%B9%CE%BA%CE%B9%CE%AC%CF%83%CE%B5%CE%B9%CF%82-%CE%B5%CE%BE%CE%BF%CF%87%CE%B9%CE%BA%CF%8E%CE%BD-%CE%BA%CE%B1%CF%84%CE%BF%CE%B9%CE%BA%CE%B9%CF%8E%CE%BD/p436144?adultsCount=2&arrival=2021-05-08&departure=2021-05-16' req = requests.get(url).text search = re.search(r'window.__INITIAL_STATE__ = ({.*});', req).group(1) data = json.loads(search) # print(data.keys()) # print(json_object) for location in data['listingReducer']['geoCode']: print(location['latitude'])
Advertisement
Answer
data['listingReducer']['geoCode']
is a dict
so doing for location in data['listingReducer']['geoCode']
gives you the keys
. . . # print(data.keys()) # print(json_object) # for location in data['listingReducer']['geoCode']: # print(location['latitude']) print(data['listingReducer']['geoCode']['latitude'])