python - 警告 : Some characters could not be decoded, 并被替换字符替换

标签 python unicode encoding web-scraping beautifulsoup

我正在创建一个脚本来从网站下载一些 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:某些字符无法解码,并被替换为替换字符。

我认为这与我使用的数据以 UTF-8 编码有关,也许 write 方法需要不同的编码?我是 Python 新手(实际上对于一般编程来说),但我陷入了困境。

最佳答案

假设你想从urls下载一些mp3文件。
您可以通过 BeautifulSoup 检索这些网址。但您不需要使用 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 url

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>

关于python - 警告 : Some characters could not be decoded, 并被替换字符替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15038402/

相关文章:

java - 对于 Java EE 开发人员来说,学习 Python/Django 有多难?

python - Django 内联表单集将始终创建新对象而不是更新它们

c# - XNA 中的 Unicode 字符串显示

Python 2.7 从utf-8文件读写 "éèàçê"

audio - FLAC音频格式是否有多种质量设置?

python - 清理 pandas 的日期时间字符串列

c - 如何在保留(非)字母数字属性的同时将多字节 UTF-8 字符表示转换为一个字节?

c++ - 什么是 : MultiByteToWideChar & WideCharToMultiByte? 的 Linux 等价物

mysql - WordPress 在其 MySQL 数据库中对其内容编码做了什么?

python - 用户定义的 __mul__ 方法不可交换