You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Python变量传入iframe标签以在Folium弹窗中展示视频

解决方法

要把Python生成的soundURL变量传递给iframe的src属性,你可以用Python的字符串格式化实现,最简洁的方式是使用f-string(Python 3.6+支持)。具体修改步骤如下:

  1. 先正确生成soundURL变量,提取YouTube短链接里的视频ID:
soundURL = sound["YouTube URL"].replace('https://youtu.be/', '')
  1. 在构建HTML内容时,用f-string将soundURL插入到iframe的src属性中,只需在HTML字符串前加f标记即可:

修改后的完整代码:

for _, sound in sounds.iterrows():
    # 提取YouTube视频ID
    soundURL = sound["YouTube URL"].replace('https://youtu.be/', '')
    # 使用f-string将soundURL插入到iframe的src中
    test = folium.Html(f'''<html>
<h1>環境音</h1>
<body>
<iframe width="420" height="345" src="https://www.youtube.com/embed/{soundURL}" ></iframe>
</body>
</html>
''', script=True)
    popup = folium.Popup(test, max_width=2650)
    folium.Marker(
        location=[sound["Latitude"], sound["Longtitude"]],
        popup=popup
    ).add_to(my_map)

my_map

兼容旧版本Python的方案

如果你的Python版本低于3.6,可以改用str.format()方法填充变量:

test = folium.Html('''<html>
<h1>環境音</h1>
<body>
<iframe width="420" height="345" src="https://www.youtube.com/embed/{}" ></iframe>
</body>
</html>
'''.format(soundURL), script=True)

内容的提问来源于stack exchange,提问作者Ryo Akita

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 07:36:23