如何编写Python代码实现音频文件的爬取与下载?

2026-05-16 17:161阅读0评论SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计295个文字,预计阅读时间需要2分钟。

如何编写Python代码实现音频文件的爬取与下载?

pythonimport json

假设这是从xmly获取的鬼故事音频列表xmly_guishi_list=[ {title: 鬼故事1, url: http://example.com/guishi1.mp3}, {title: 鬼故事2, url: http://example.com/guishi2.mp3}, {title: 鬼故事3, url: http://example.com/guishi3.mp3}]

将列表转换为JSON格式json_data=json.dumps(xmly_guishi_list, ensure_ascii=False)

输出JSON数据print(json_data)

如何编写Python代码实现音频文件的爬取与下载?

抓取“xmly”鬼故事音频

import json # 在这个url,音频链接为JSON动态生成,所以用到了json模块 import requests headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36" } # 请求网页 def open_url(url): r = requests.get(url, headers=headers) r.encoding = 'utf-8' html = r.text # 将JSON转化成字符串 html = json.loads(html) return html # 得到所有音频的链接 def get_urls(url): us = url['data']['tracksAudioPlay'] return us def main(): num = 1 url = 'www.ximalaya.com/revision/play/album?albumId=4256765&pageNum=1&sort=-1&pageSize=30' html = open_url(url) urls = get_urls(html) # 遍历得到每个音频的链接和对应的名称 for ul in urls: uls = ul['src'] filename = ul['trackName'] reponse = requests.get(uls).content with open(filename + '.m4a', 'wb') as file: file.write(reponse) print(str(num) + '. ' + filename) num += 1 if __name__ == '__main__': main()

爬取结果

以上就是python爬取音频下载的示例代码的详细内容,更多关于Python 爬取音频下载的资料请关注易盾网络其它相关文章!

本文共计295个文字,预计阅读时间需要2分钟。

如何编写Python代码实现音频文件的爬取与下载?

pythonimport json

假设这是从xmly获取的鬼故事音频列表xmly_guishi_list=[ {title: 鬼故事1, url: http://example.com/guishi1.mp3}, {title: 鬼故事2, url: http://example.com/guishi2.mp3}, {title: 鬼故事3, url: http://example.com/guishi3.mp3}]

将列表转换为JSON格式json_data=json.dumps(xmly_guishi_list, ensure_ascii=False)

输出JSON数据print(json_data)

如何编写Python代码实现音频文件的爬取与下载?

抓取“xmly”鬼故事音频

import json # 在这个url,音频链接为JSON动态生成,所以用到了json模块 import requests headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36" } # 请求网页 def open_url(url): r = requests.get(url, headers=headers) r.encoding = 'utf-8' html = r.text # 将JSON转化成字符串 html = json.loads(html) return html # 得到所有音频的链接 def get_urls(url): us = url['data']['tracksAudioPlay'] return us def main(): num = 1 url = 'www.ximalaya.com/revision/play/album?albumId=4256765&pageNum=1&sort=-1&pageSize=30' html = open_url(url) urls = get_urls(html) # 遍历得到每个音频的链接和对应的名称 for ul in urls: uls = ul['src'] filename = ul['trackName'] reponse = requests.get(uls).content with open(filename + '.m4a', 'wb') as file: file.write(reponse) print(str(num) + '. ' + filename) num += 1 if __name__ == '__main__': main()

爬取结果

以上就是python爬取音频下载的示例代码的详细内容,更多关于Python 爬取音频下载的资料请关注易盾网络其它相关文章!