如何在 python 中定位字符串和整数数据

How do I locate string and integer data in python

我想从页面源中找到此数据

"location": {"latitude": 35.4677026, "longitude": -80.6093396}

目前我是运行这个代码

floats = re.findall(r"[-+]?\d+\.\d+", str(soup))
  for i in range(len(floats)):
      if len(floats[i]) > 9:
        LatLong.append(floats[i])

输出有我要找的数据,但也有我不希望混入的数据

import json

string_data = '{"location": {"latitude": 35.4677026, "longitude": -80.6093396}}'

data = json.loads(string_data)

if 'location' in data:
    # do something with the data
    print(data['location']['latitude'])
    print(data['location']['longitude'])

您应该验证数据字典中是否存在使用的键以避免字典键错误