如何将Python变量传入iframe标签以在Folium弹窗中展示视频
解决方法
要把Python生成的soundURL变量传递给iframe的src属性,你可以用Python的字符串格式化实现,最简洁的方式是使用f-string(Python 3.6+支持)。具体修改步骤如下:
- 先正确生成
soundURL变量,提取YouTube短链接里的视频ID:
soundURL = sound["YouTube URL"].replace('https://youtu.be/', '')
- 在构建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
相关产品推荐
相关产品推荐

