【问题标题】:How to fix Cyrillic characters while web-scraping with Python如何在使用 Python 进行网页抓取时修复西里尔字符
【发布时间】:2019-09-12 01:07:06
【问题描述】:

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

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

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

我的代码是这样的:

from bs4 import BeautifulSoup
import requests

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

soup = BeautifulSoup(source, 'lxml')

print(soup.prettify())

我应该如何解决它?

【问题讨论】:

    标签: python web-scraping beautifulsoup character-encoding cyrillic


    【解决方案1】:

    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
    

    【讨论】:

    • 该站点不提供内容类型标头,因此requests 回退到 ISO-8859-1/latin-1。然而,在定义字符集的 html 中有一个元标记,因此另一种方法可能是将source.content 传递给BeautifulSoup 并让BeautifulSoup 处理解码。
    • 当我添加这一行“source.encoding = 'utf-8'”时我没有任何错误但输出为空白!?你有什么结果吗?
    • @scpbook 设置变量不会打印任何内容。就像foo = 42 不会打印任何东西,除非你print(foo)。您可以在下一行添加print(source.encoding) 来测试它,或者只是看看它是否解决了您的问题。至少对我来说是这样。
    • @PatrykBratkowski 当然我在打印它,我的代码:from bs4 import BeautifulSoup import requests source = requests.get('https://time.mk/') source.encoding = 'utf-8' soup = BeautifulSoup(source.text, 'lxml') print(soup) 它显示我有 2740 行文本,但是当我打开它时它是空的。
    • @scpbook 如果您现在遇到不同的问题,我认为您应该发一个新帖子,因为 SO 并不适合在 cmets 中讨论。 The code I posted definitely works.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-21
    • 1970-01-01
    • 2020-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多