首页 > 解决方案 > Python:运行应用程序时如何在浏览器中打开用folium创建的地图

问题描述

我有一个使用 python3 用 PyCharm 编写的非常小的应用程序:

import folium

map = folium.Map(location=[58.1, 23.3], zoom_start=10)
map.save('map2.html')

这将创建一个map2.html我可以使用 pycharm 在我的浏览器中访问的,并且 url 看起来像:http://localhost:63342/iss-country/map2.html?_ijt=dcsefdg8om4ddfovlt5ooq6ro5

如何在浏览器中自动打开它?因此,当我运行应用程序时,它不仅会生成 html 页面,还会立即访问它。我找到了webbrowser有用的模块,但我怎么知道正确的 localhost url?

标签: pythonpython-3.x

解决方案


我没有看到使用webbrowser模块的问题。只需将文件名和路径设为变量并调用 webbrowser open 方法。

output_file = "map2.html"
map = folium.Map(location=[58.1, 23.3], zoom_start=10)
map.save(output_file)
webbrowser.open(output_file, new=2)  # open in new tab

推荐阅读