在文本文件上书写时,重音符号和特殊字符无法正确显示

Ser*_*raf 5 python encoding utf-8 web-crawler utf

这就是我正在做的事情,我在网站上进行网络爬虫以供个人使用,以复制文本并将书籍的章节设置为文本格式,然后使用另一个程序将其自动转换为 pdf 以将其放入我的云中。一切都很好,直到发生这种情况:特殊字符无法正确复制,例如重音在文本文件上显示为:\xe2\x80\x99,而 - 显示为\xe2\x80\x93。我用过这个(Python 3):

    for text in soup.find_all('p'):
        texta = text.text
        f.write(str(str(texta).encode("utf-8")))
        f.write('\n')
Run Code Online (Sandbox Code Playgroud)

因为我在读取这些字符时遇到了错误并且它刚刚停止了我的程序,所以我将所有内容编码为 utf-8 并使用 python 的方法 str() 将所有内容重新转换为字符串

如果有人对我的问题有更好的解决方案,我将发布整个代码,这是从第 1 页爬行网站到 max_pages 的部分,您可以在第 21 行修改它以获取本书的更多或更少章节:

import requests

from bs4 import BeautifulSoup

def crawl_ATG(max_pages):
    page = 1
    while page <= max_pages:
        x= page
        url = 'http://www.wuxiaworld.com/atg-index/atg-chapter-' + str(x) + "/"
        source = requests.get(url)
        chapter = source.content
        soup = BeautifulSoup(chapter.decode('utf-8', 'ignore'), 'html.parser')
        f = open('atg_chapter' + str(x) + '.txt', 'w+')
        for text in soup.find_all('p'):
        texta = text.text
            f.write(str(str(texta).encode("utf-8")))
            f.write('\n')
        f.close
        page +=1
    
crawl_ATG(10)
Run Code Online (Sandbox Code Playgroud)

当我得到这个问题的解决方案时,我将清理稍后复制的第一批无用的行。谢谢

mem*_*lyk 0

我能发现的唯一错误是,

str(texta).encode("utf-8")
Run Code Online (Sandbox Code Playgroud)

在其中,您强制转换为 str 并对其进行编码。它应该替换为,

texta.encode("utf-8")
Run Code Online (Sandbox Code Playgroud)

编辑:

该错误源于服务器没有为页面提供正确的编码。所以requests假设一个'ISO-8859-1'. 正如此错误中所指出的,这是一个经过深思熟虑的决定。

幸运的是,chardet库可以正确检测'utf-8'编码,因此您可以执行以下操作:

source.encoding = source.apparent_encoding
chapter = source.text
Run Code Online (Sandbox Code Playgroud)

并且不需要手动解码 中的文本chapter,因为requests使用它来为您解码content