为什么我不能下载带有python请求的midi文件?

时间:2018-09-01 03:58:16

标签: python download python-requests web-crawler midi

我正在尝试使用python和请求库下载一系列古典音乐midi文件。不幸的是,我似乎无法实际下载Midi文件本身。我要下载的唯一内容是HTML文件。我已经搜索过SO,并尝试了其他一些解决方案,例如this postthis post,但两种解决方案都不适合我。

这是我编写的代码:

from bs4 import BeautifulSoup
import requests
import re

url = 'http://www.midiworld.com/classic.htm'
headers = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
r = requests.get(url, headers=headers)
data = r.text
soup = BeautifulSoup(data, "html.parser")

links = []
for link in soup.find_all("a", href=re.compile("mid$")):
    links.append(link['href'])


def get_filename(links):
    filenames = []
    """
    Will return a list of filenames for the files to be downloaded
    """
    for link in links:
        url = link
        if url.find('/'):
            f_name = url.rsplit('/', 1)[1]
            print(url.rsplit('/', 1)[1])
            filenames.append(f_name)
    return filenames


def download_files(links, filenames):
    for link, filename in zip(links, filenames):
        r = requests.get(url, allow_redirects=True)
        with open(filename, 'wb') as saveMidi:
            saveMidi.write(r.content)

filenames = get_filename(links)
download_files(links, filenames)

我不知道为什么我要返回HTML文件。关于如何正确下载Midi文件的任何想法?

3 个答案:

答案 0 :(得分:1)

我不知道为什么,但这对我有用。

from urllib.request import urlopen
x = urlopen(links[0]).read()
with open(filenames[0], "wb") as f:
    f.write(x)

答案 1 :(得分:1)

我解决了这个问题,但是我不得不对您的代码进行一些重大更改。修改后的代码:

import requests
from bs4 import BeautifulSoup
import re

main_page = requests.get('http://www.midiworld.com/classic.htm')
parsed_page = BeautifulSoup(main_page.content, 'html.parser')

links = parsed_page.find_all('a', href=re.compile('mid$'))
def getFileName(link):
    link = link['href']
    filename = link.split('/')[::-1][0]
    return filename

def downloadFile(link, filename):
    mid_file = requests.get(link['href'], stream=True)
    with open(filename, 'wb') as saveMidFile:
        saveMidFile.write(mid_file.content)
        print('Downloaded {} successfully.'.format(filename))

for link in links:
    filename = getFileName(link)
    downloadFile(link, filename)

这似乎可以快速,轻松地下载文件。它们都没有损坏,我可以很好地播放它们。 感谢您用古典音乐让我的主文件夹杂乱无章。

答案 2 :(得分:0)

如果有人想使用贝壳咒语:

wget https://www.midiworld.com/mozart.htm
cat mozart.htm | grep -oh -E 'https(.*)\.mid"' | sed 's/"//' | xargs wget -c -t1
rm mozart.htm