思路
选择对应的区域其实是按照表格中的省市区的名字进行匹配
读取文件后对应的字典为:
{'台湾': {},'新疆': {},'港澳': {'中国澳门': ['凼仔岛', nan]},'西藏': {'昌都地区': ['卡若区'], '那曲地区': [nan]}
}
字典解释例如
市区为空,就是选择省下面的全部市和区
区为空,就是选择市下面的全部的区
全都不为空,就是选择该省该市的区
读取文件
import numpy as np
import pandas as pdareas_df = pd.read_excel(excel_file, sheet_name='禁售区域')read_areas_dict = areas_df.groupby('省').apply(lambda x: x.groupby('市')['区'].apply(list).to_dict()).to_dict()"""
读取文件后【read_areas_dict 】的值为一个字典:
{'台湾': {}, '新疆': {}, '港澳': {'中国澳门': ['凼仔岛', nan]}, '西藏': {'昌都地区': ['卡若区'], '那曲地区': [nan]}}
"""
匹配区域
areas_data 就是读取文件后的字典
all_areas_dict是博主上一篇博文所获取的区域id_dict,这里只对已获取的数据进行解析,由由需要的话查看区域id是如何获取的:获取全部的地区并生成表格_gongzairen的博客-CSDN博客
customParam 是我要发送请求所需要的参数,每个网站不一样,自行设置就好
import mathdata_dict = {'data': "",'error_info': '无','warning_info': '无',
}# 三层嵌套处理省市区对应的id
areas_data = {'读取文件后的字典'}
all_areas_dict = {'全部的区域id字典'}
customParam = ""
for province_name in areas_data:# 处理省idif province_name in areas_id_dict:province_id = areas_id_dict[province_name]['id']city_name_list = list(areas_data[province_name].keys())# 省全选的情况if not city_name_list:customParam += f"areaLevel:{areas_id_dict[province_name]['level']}|areaId:{province_id}|parentId:0|parentOneId:0,"continue# 处理市idfor city_name in city_name_list:if city_name == 'id' or city_name == 'level' or city_name == 'parentId':continueif city_name in list(areas_data[province_name].keys()):city_id = areas_id_dict[province_name][city_name]['id']else:data_dict['warning_info'] += "\n" + f'{city_name}:找不到对应的市,请确保城市名字正确,否则请联系开发人员更新地区id'continuedistrict_list = areas_data[province_name][city_name]# 市全选的情况is_nan = any(math.isnan(x) for x in district_list if isinstance(x, float))if is_nan:customParam += f"areaLevel:{areas_id_dict[province_name]['level']}|areaId:{city_id}|parentId:{province_id}|parentOneId:0,"# print(f'customParam:{customParam}')continuefor district_name in district_list:# print(district_name)if district_name == 'id' or district_name == 'level' or district_name == 'parentId':continueif district_name in list(areas_id_dict[province_name][city_name].keys()):# print(district_name)district_id = areas_id_dict[province_name][city_name][district_name]['id']customParam += f"areaLevel:{areas_id_dict[province_name]['level']}|areaId:{district_id}|parentId:{city_id}|parentOneId:,"else:data_dict['warning_info'] += "\n" + f'{district_name}:找不到对应的区,请确保区名字正确,否则请联系开发人员更新地区id'continueelse:data_dict['warning_info'] += "\n" + f'{province_name}:找不到对应的省,请确保省份名字正确,否则请联系开发人员更新地区id'continue