key用自己申请的
def handle_detail_and_save_to_csv(poi_list, city, province_):
"""
处理POI详情信息并保存到CSV文件
:param city:
:param province_:
:param poi_list: POI数据列表
:return: None
"""
# 配置Selenium WebDriver
chrome_options = Options()
chrome_options.add_argument("--headless") # 无头模式
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=chrome_options)
# Excel文件名
xlsx_filename = '../Main/search/stations/province_data.xlsx'
base_url = "https://www.amap.com/place/"
# 检查Excel文件是否存在以及是否为空
file_exists = False
try:
wb = openpyxl.load_workbook(xlsx_filename)
sheet = wb.active
file_exists = True
except FileNotFoundError:
wb = openpyxl.Workbook()
sheet = wb.active
# 如果文件为空或不存在,则写入表头
if not file_exists:
sheet.append(["省份", "城市", "名称", "地址", "电话", "经度", "纬度", "POI ID", "详情链接"])
try:
# 遍历 POI 列表,提取详细信息并写入 Excel
for poi in poi_list:
poi_id = poi.get('id')
if not poi_id:
continue # 如果没有POI ID,则跳过此项
# 获取POI详细页面
driver.get(f"{base_url}{poi_id}")
# 等待页面加载,假设页面有个元素用于标识详情加载完成
driver.implicitly_wait(5)
# 获取页面内容(你可以根据页面结构选择适当的获取方式)
detail_json = driver.execute_script('return window.__INITIAL_STATE__') # 假设页面数据存储在__INITIAL_STATE__
print(detail_json)
province1 = province_
city1 = city
# 从详细页面中提取必要的信息
poi_name = poi.get('name', '无名称')
poi_address = poi.get('address', '无地址')
poi_phone = poi.get('tel', '无电话')
poi_location = poi.get('location', '无经纬度').split(',')
longitude = poi_location[0] if len(poi_location) > 0 else '无经度'
latitude = poi_location[1] if len(poi_location) > 1 else '无纬度'
# 只有在数据有效的情况下,才将数据写入Excel文件
row_data = [province1, city1, poi_name, poi_address, poi_phone, longitude, latitude, poi_id,
f"{base_url}{poi_id}"]
if all(row_data): # 如果行数据不为空,则写入
sheet.append(row_data)
print(f"{poi_id} 详细信息已写入Excel文件.")
else:
print(f"{poi_id} 数据为空,跳过.")
except Exception as e:
print(f"发生错误: {e}")
finally:
# 保存 Excel 文件
wb.save(xlsx_filename)
print(f"数据已保存到 {xlsx_filename}")
# 关闭浏览器
driver.quit()
仅供参考学习,要源码的,后台滴我