我正在创建一个脚本,以从站点下载一些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()


运行代码时,在控制台中收到以下警告:

警告:root:某些字符无法解码,并由REPLACEMENT CHARACTER替换。

我认为这与以下事实有关:我使用的数据是以UTF-8编码的,也许write方法期望使用不同的编码?我是Python的新手(实际上是一般编程人员),但是我很固执。

最佳答案

假设您要从网址下载一些mp3文件。
您可以通过BeautifulSoup检索这些URL。但是您不需要使用BeautifulSoup来解析URL。您只需要直接保存即可。
例如,

url = 'http://acl.ldc.upenn.edu/P/P96/P96-1004.pdf'
res = urllib2.urlopen(url)
with open(fileName, 'wb') as fp:
    fp.write(res.read())


如果我使用BeautifulSoup解析该pdf网址

reqSoup = BeautifulSoup('http://acl.ldc.upenn.edu/P/P96/P96-1004.pdf')


reqSoup不是pdf文件,而是HTML响应。其实是

<html><body><p>http://acl.ldc.upenn.edu/P/P96/P96-1004.pdf</p></body></html>

10-04 11:05
查看更多