首页 > 解决方案 > 如何在使用 Python 进行网络抓取时修复西里尔字符

问题描述

我正在使用 BeautifulSoup 用 python 抓取一个西里尔文网站,但我遇到了一些麻烦,每个单词都显示如下:

С¡¡¸Ð»ÑановÑка С°Ð²ÐºÐ¾Ð²Ð° во С°Ð·Ð¸

我还尝试了其他一些西里尔文网站,但它们运行良好。

我的代码是这样的:

from bs4 import BeautifulSoup
import requests

source = requests.get('https://').text

soup = BeautifulSoup(source, 'lxml')

print(soup.prettify())

我应该如何解决它?

标签: pythonweb-scrapingbeautifulsoupcharacter-encodingcyrillic

解决方案


requests未能将其检测为utf-8.

from bs4 import BeautifulSoup
import requests

source = requests.get('https://time.mk/')  # don't convert to text just yet

# print(source.encoding)
# prints out ISO-8859-1

source.encoding = 'utf-8'  # override encoding manually

soup = BeautifulSoup(source.text, 'lxml')  # this will now decode utf-8 correctly

推荐阅读