首页 > 解决方案 > BeautifulSoup 中的“'ascii' 编解码器无法编码字符”错误

问题描述

Python新手在这里。目前正在为一个歌词网站编写爬虫,我在尝试解析 HTML 时遇到了这个问题。我正在使用 BeautifulSoup 和请求。

现在的代码是(毕竟导入等等):

import requests as r
from bs4 import BeautifulSoup as bs

def function(artist_name):
    temp = "https://www.lyrics.com/lyrics/"
    if ' ' in artist_name:
        artist_name = artist_name.replace(' ', '%20')
    page = r.get(temp + artist_name.lower()).content
    soup = bs(page, 'html.parser')
    return soup

当我尝试对此进行测试时,我不断收到以下错误:

UnicodeEncodeError: 'ascii' codec can't encode character '\xa0' in position 8767: ordinal not in range(128)

我尝试添加.encode('utf-8')soup行尾,它消除了错误,但不允许我使用任何 BeautifulSoup 方法,因为它返回字节。

我查看了此处的其他帖子,并尝试了他们为类似错误提供的其他解决方案。关于 Python 和 Unicode,我还有很多需要了解的地方,但如果有人可以提供帮助并提供一些指导,我将不胜感激。

标签: pythonpython-3.xbeautifulsouppython-requests

解决方案


推荐阅读