我正在创建一个脚本来从一个站点下载一些 mp3 播客并将它们写入某个位置。我快完成了,正在下载和创建文件。但是,我遇到了无法完全解码二进制数据并且无法播放 mp3 文件的问题。
这是我的代码:
import re
import os
import urllib2
from bs4 import BeautifulSoup
import time
def getHTMLstring(url):
html = urllib2.urlopen(url)
soup = BeautifulSoup(html)
soupString = soup.encode('utf-8')
return soupString
def getList(html_string):
urlList = re.findall('(http://podcast\.travelsinamathematicalworld\.co\.uk\/mp3/.*\.mp3)', html_string)
firstUrl = urlList[0]
finalList = [firstUrl]
for url in urlList:
if url != finalList[0]:
finalList.insert(0,url)
return finalList
def getBinary(netLocation):
req = urllib2.urlopen(netLocation)
reqSoup = BeautifulSoup(req)
reqString = reqSoup.encode('utf-8')
return reqString
def getFilename(string):
splitTerms = string.split('/')
fileName = splitTerms[-1]
return fileName
def writeFile(sourceBinary, fileName):
with open(fileName, 'wb') as fp:
fp.write(sourceBinary)
def main():
htmlString = getHTMLstring('http://www.travelsinamathematicalworld.co.uk')
urlList = getList(htmlString)
fileFolder = 'D:\\Dropbox\\Mathematics\\Travels in a Mathematical World\\Podcasts'
os.chdir(fileFolder)
for url in urlList:
name = getFilename(url)
binary = getBinary(url)
writeFile(binary, name)
time.sleep(2)
if __name__ == '__main__':
main()
当我运行代码时,我在控制台中收到以下警告:
警告:根:某些字符无法解码,并被替换为替换字符。
我认为这与我使用的数据以 UTF-8 编码这一事实有关,也许 write 方法需要不同的编码?我是 Python 新手(实际上是一般编程),我被困住了。