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

如何用Python结合BeautifulSoup或Selenium下载并保存指定链接的音频?

Python下载指定音频文件的方法

一、直接HTTP请求下载(最简便)

你已经拿到了音频的直接下载链接,这种情况下不需要用到BeautifulSoup(它主要用于解析HTML页面提取内容),直接用requests库发送请求即可。注意要设置请求头模拟浏览器,避免被服务器拦截:

import requests

audio_url = "https://translate.google.com/translate_tts?ie=UTF-8&client=tw-ob&tl=en&q=how%27s%20the%20weather%20today?"
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
}

response = requests.get(audio_url, headers=headers)
if response.status_code == 200:
    with open("weather_audio.mp3", "wb") as f:
        f.write(response.content)
    print("音频已保存为 weather_audio.mp3")
else:
    print(f"下载失败,状态码:{response.status_code}")

二、使用Selenium下载(模拟浏览器场景)

如果遇到服务器拦截普通HTTP请求,可使用Selenium模拟真实浏览器行为下载:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time

# 配置Chrome下载选项
chrome_options = Options()
download_dir = "./"  # 设置下载目录为当前文件夹
chrome_options.add_experimental_option("prefs", {
    "download.default_directory": download_dir,
    "download.prompt_for_download": False,
    "download.directory_upgrade": True
})

# 启动浏览器
driver = webdriver.Chrome(options=chrome_options)

try:
    driver.get("https://translate.google.com/translate_tts?ie=UTF-8&client=tw-ob&tl=en&q=how%27s%20the%20weather%20today?")
    time.sleep(3)  # 等待下载完成,根据网速调整时间
    print(f"音频已下载到:{download_dir}")
finally:
    driver.quit()

注意:使用Selenium前需安装对应浏览器的驱动(如ChromeDriver),且驱动版本要与浏览器版本一致。

内容的提问来源于stack exchange,提问作者Jun K.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 10:45:33