iGa*_*ers 6 python mp3 download python-3.x python-requests
我正在尝试学习 Python,并尝试编写一段代码来从我的教堂网站下载所有圣经 mp3 文件,其中有一个 mp3 超链接列表,例如:
第1章、第2、3、4、5章等等...参考链接
运行我的代码后,我设法让所有 mp3 URL 链接显示在 shell 上,但我似乎根本无法下载它们。
这是我的代码
import requests
import urllib.request
import re
from bs4 import BeautifulSoup
r = requests.get('https://ghalliance.org/resource/bible-reading')
soup = BeautifulSoup(r.content, 'html.parser')
for a in soup.find_all('a', href=re.compile('http.*\.mp3')):
print(a['href'])
Run Code Online (Sandbox Code Playgroud)
我确实尝试使用 wget 但我似乎无法让 wget 在运行 VSCode Python 3.8.1 64 位或 conda 3.7.4 的机器上工作...我检查了 conda cmd 和 cmd ,它表明我我的系统中有 wget,我什至手动将 wget.exe 下载到我的 system32 目录,但每当我尝试运行
wget.download(url)
Run Code Online (Sandbox Code Playgroud)
我总是收到错误消息或类似 wget 没有属性“下载”之类的信息。
我读了一些关于使用 selenium、wget、beautifulsoup 下载简单图片等的初学者教程,但我似乎无法合并他们的方法来解决我的这个特定问题......因为我对编程还太陌生一般来说,所以我为问这些愚蠢的问题而道歉。
但现在我有了所有 MP3 URL 链接,所以我的问题是:如何使用 Python 下载它们?
小智 10
由于您已经使用了库,因此requests
您还可以使用它requests来下载 mp3(或任何文件)
例如,如果您想从 URL 下载文件https://test.ghalliance.org/resources//bible_reading/audio/Chiv Keeb 01.mp3
doc = requests.get(https://test.ghalliance.org/resources//bible_reading/audio/Chiv%20Keeb%2001.mp3)
Run Code Online (Sandbox Code Playgroud)
如果下载成功。mp3 内容将存储在其中,doc.content然后您需要打开文件并将数据写入该文件。
with open('myfile.mp3', 'wb') as f:
f.write(doc.content)
Run Code Online (Sandbox Code Playgroud)
此时,您已拥有文件名为“myfile.mp3”的 mp3,但您可能希望保存到与 URL 中的名称相同的文件名。
让我们从 URL 中提取文件名。
filename = a['href'][a['href'].rfind("/")+1:]
with open(filename, 'wb') as f:
f.write(doc.content)
Run Code Online (Sandbox Code Playgroud)
现在让我们把它们放在一起。
import requests
import urllib.request
import re
from bs4 import BeautifulSoup
r = requests.get('https://ghalliance.org/resource/bible-reading')
soup = BeautifulSoup(r.content, 'html.parser')
for a in soup.find_all('a', href=re.compile(r'http.*\.mp3')):
filename = a['href'][a['href'].rfind("/")+1:]
doc = requests.get(a['href'])
with open(filename, 'wb') as f:
f.write(doc.content)
Run Code Online (Sandbox Code Playgroud)
请注意:
requests.Session()来维护TCP连接会话,而不是重复打开文件的socket操作closing。stream=True来避免损坏的下载。.status_codefor检查状态response。Chiv Keeb 22mp3以及Cov Thawjtswj 01mp3扩展名应该在哪里.mp3。以下是实现您目标的正确代码。
import requests
from bs4 import BeautifulSoup
import re
r = requests.get("https://ghalliance.org/resource/bible-reading/")
soup = BeautifulSoup(r.text, 'html.parser')
with requests.Session() as req:
for item in soup.select("#playlist"):
for href in item.findAll("a"):
href = href.get("href")
name = re.search(r"([^\/]+$)", href).group()
if '.' not in name[-4]:
name = name[:-3] + '.mp3'
else:
pass
print(f"Downloading File {name}")
download = req.get(href)
if download.status_code == 200:
with open(name, 'wb') as f:
f.write(download.content)
else:
print(f"Download Failed For File {name}")
Run Code Online (Sandbox Code Playgroud)