Python calls Baidu map api, queries the latitude and longitude of the place, and writes the data into excel

1. Introduction

Python calls Baidu map api, queries the latitude and longitude of the place, and writes the data into excel

2. Software environment

2.1vsCode

2.2 He liked

version: conda 22.9.0

3. Main process

3.1 Call the Baidu map api to query the latitude and longitude of the place

Create an account first After entering the Baidu map API
, create an account first. After the account is created, click the console in the upper right corner
insert image description here
to create an application
insert image description here
insert image description here
, and then directly run the code I pasted
. Paste the code

import requests

# 精度维度查找函数
def seekLocation(address):
    # API的URL
    url = 'http://api.map.baidu.com/geocoding/v3/'

    # 构建请求参数
    params = {
    
    
        'ak': '这块要换成自己的ak的',
        'output': 'json',
        'address': '南京航空航天大学',  # 替换为您要查询的地方名称
    }
    params['address'] = address
    # 发送GET请求
    response = requests.get(url, params=params)

    # 检查响应状态码
    if response.status_code == 200:
        # 解析返回的JSON数据
        data = response.json()
        # 检查结果状态
        if data['status'] == 0:
            # 提取经度和纬度
            location = data['result']['location']
            return location
        else:
            print('地理编码失败:', data['message'])
    else:
        print('请求出错:', response.status_code)


location = seekLocation('河南师范大学')
latitude = location['lat']
longitude = location['lng']
# 打印经度和纬度
print('经度:', longitude)
print('纬度:', latitude)

3.2 Read excel data

Just change the corresponding column

from openpyxl import load_workbook

# 打开Excel文件
workbook = load_workbook(filename='school2.xlsx')

# 选择要操作的表单
sheet = workbook['Sheet1']
column_values = []
for column in sheet.iter_cols(min_col=2, max_col=2, values_only=True):
    column_values.append(column)
print(column_values)

3.3 Write excel data

from openpyxl import load_workbook

# 打开Excel文件
workbook = load_workbook(filename='school2.xlsx')
sheet = workbook['Sheet1']
sheet.cell(row=row_index, column=8, value=value)
# 保存 Excel 文件
workbook.save(filename='school2.xlsx')
# 关闭 Excel 文件
workbook.close()

3.4 Complete code

Installation package

! pip install openpyxl
! pip install requests

the code

from openpyxl import load_workbook
import requests

# 输入学校
def seekLocation(address):
    # API的URL
    url = 'http://api.map.baidu.com/geocoding/v3/'

    # 构建请求参数
    params = {
    
    
        'ak': '换成自己的',
        'output': 'json',
        'address': '南京航空航天大学',  # 替换为您要查询的地方名称
    }
    params['address'] = address
    # 发送GET请求
    response = requests.get(url, params=params)

    # 检查响应状态码
    if response.status_code == 200:
        # 解析返回的JSON数据
        data = response.json()
        # 检查结果状态
        if data['status'] == 0:
            # 提取经度和纬度
            location = data['result']['location']
            return location
        else:
            print('地理编码失败:', data['message'])
    else:
        print('请求出错:', response.status_code)

# 读写程序
'''
file:读写的文件
col1:要读哪一列
col2:纬度写入的列
col3:经度度写入的列
'''
def readWrite(file,col1,col2,col3):
    # 打开Excel文件
    workbook = load_workbook(filename=file)

    # 选择要操作的表单
    sheet = workbook['Sheet1']
    column_values = []
    for column in sheet.iter_cols(min_col=col1, max_col=col1, values_only=True):
        column_values.append(column)

    row_index = 1# 指定行索引,例如第2行
    lastLat = 0# 保存上步纬度
    lastLng = 0# 保存上步精度
    for value in column_values[0]:
        if value == None:
            # 第八列是纬度,
            sheet.cell(row=row_index, column=col2, value=0)
            # 第九列是经度
            sheet.cell(row=row_index, column=col3, value=0)
            row_index = row_index + 1
            continue

        location = seekLocation(value)
        latitude = location['lat']
        longitude = location['lng']

        if lastLat == latitude and lastLng == longitude:
            sheet.cell(row=row_index-1, column=col3+1, value="重复")
            sheet.cell(row=row_index, column=col3+1, value="重复")


        lastLat = latitude
        lastLng = longitude
        # 打印经度和纬度
        print("学校:{},经度:{},纬度:{}".format(value, longitude, latitude))
        # 写入值到指定行列
        # 第八列是纬度,
        sheet.cell(row=row_index, column=col2, value=latitude)
        # 第九列是经度
        sheet.cell(row=row_index, column=col3, value=longitude)
        row_index = row_index + 1

    # 保存 Excel 文件
    workbook.save(filename=file)
    # 关闭 Excel 文件
    workbook.close()
    print("写入完成!!!")


'''
file:读写的文件(文件名字尽量不要中文)
col1:要读哪一列
col2:纬度写入的列
col3:经度度写入的列
'''
file = "school3.xlsx"
col1 = 2
col2 = 8
col3 = 9
readWrite(file,col1,col2,col3)

insert image description here

Guess you like

Origin blog.csdn.net/qq_45179361/article/details/131297014