首页 > 解决方案 > 如何在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])

输出有我正在寻找的数据,但它也有我不想要的数据混入其中

标签: pythonstringbeautifulsoupdata-extraction

解决方案


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'])

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


推荐阅读