Python网站scraper UnicodeEncodeE

2024-10-02 08:22:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python3.4中使用Requests和BeautifulSoup从一个可能包含也可能不包含日语或其他特殊字符的网站上获取信息。在

def startThisPage(url):
    r = requests.get(str(url))
    r.encoding="utf8"
    print(r.content.decode('utf8'))
    soup = BeautifulSoup(r.content,'html.parser')
    print(soup.h2.string)

h2包含这样的内容:“命运/卡莱德班轮普里斯玛☆伊利亚·兹维!”我很确定现在给我带来麻烦的是明星。在

向我抛出的错误代码:

^{pr2}$

这个页面是用utf8编码的,因此我尝试用utf8对r.content接收到的字节串进行编码和解码。我也尝试过先用unicode_escape进行解码,以为是因为double\的缘故,但事实并非如此。有什么想法吗?在


Tags: url编码网站defh2contentutf8解码
1条回答
网友
1楼 · 发布于 2024-10-02 08:22:13

soup.h2.string是Unicode字符串。控制台字符编码(如cp437)不能表示导致错误的一些Unicode字符(☆U+2606 WHITE STAR)。要解决此问题,请参见my answer to "Python, Unicode, and the Windows console" question。在

I still get the same error trying to write to a file..

默认情况下,文件(使用open()创建)使用locale.getpreferredencoding(False),如cp1252。请改用支持完整Unicode范围的显式字符编码:

import io

with io.open('title.txt', 'w', encoding='utf-8') as file:
    file.write(soup.h2.string)

相关问题 更多 >

    热门问题