我正在尝试学习Python,并且尝试编写代码从教堂网站上下载所有圣经mp3文件,那里有mp3超链接列表,例如: 第1章第2、3、4、5章,依此类推... Reference link 运行代码后,我设法在外壳上显示了所有的mp3 URL链接,但我似乎根本无法下载它们。 这是我的代码 我确实尝试过使用wget,但是我似乎无法在运行VSCode Python 3.8.1 64位或conda 3.7.4的计算机上使用wget进行工作...我已经检查了conda cmd和cmd以及它显示我的系统中有wget,我什至手动将wget.exe下载到我的system32目录,但是每当我尝试运行 我总是收到错误消息,或者类似wget的东西没有“下载”或“不”属性。 我阅读了一些有关使用硒,wget,beautifulsoup下载简单图片等的初学者教程,但是我似乎无法将他们的方法用于解决我的这个特定问题...因为我还是太新了总体上讲编程,所以我为这样的愚蠢愚蠢的问题而道歉。 但是,既然我拥有所有的MP3 URL链接,我想我的问题是,
如何使用python下载它们?如果有人可以帮忙,将不胜感激。 答案 0 :(得分:1) 使用 答案 1 :(得分:0) 请注意: 下面是实现您的目标的正确代码。 答案 2 :(得分:0) 您已经在使用库 例如您要从URL 如果下载成功。 mp3内容将存储在 目前,您的mp3文件名为“ myfile.mp3”,但您可能希望将其保存为与URL中的名称相同的文件名。 从URL中提取文件名。 现在让它们放在一起。NumberUtils
StringUtils
3 个答案:
import requests
import urllib.request
import re
from bs4 import BeautifulSoup
i=0
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')):
i=i+1
url = a['href']
file=url.split()[1]
urllib.request.urlretrieve(url, f"{file}_{i}.mp3")
urllib.request.urlretrieve(url, filename=None)
可以将URL表示的网络对象复制到本地文件。
requests.Session()
来维持TCP
连接会话,而不要重复执行打开socket
和closing
的操作。 stream=True
来防止损坏的下载。.status_code
作为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}")
requests
您还可以使用requests
下载mp3(或任何文件)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)
doc.content
中,然后您需要打开文件并将数据写入该文件。with open('myfile.mp3', 'wb') as f:
f.write(doc.content)
filename = a['href'][a['href'].rfind("/")+1:]
with open(filename, 'wb') as f:
f.write(doc.content)
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)