gpt4 book ai didi

python - 如何知道什么是正确的编码?

转载 作者:太空宇宙 更新时间:2023-11-03 17:01:37 26 4
gpt4 key购买 nike

我决定学习 C++,而且我非常喜欢 www.learncpp.com 这个网站。现在,我想制作一个 pdf 版本并打印出来,以便我可以在纸上阅读。首先,我构建了网站中所有章节的 url 收集器。效果很好。

现在我正在努力从 first chapter 创建一个 html 。我写了以下内容:

import requests
from bs4 import BeautifulSoup
import codecs

req = requests.get("http://www.learncpp.com/cpp-tutorial/01-introduction-to-these-tutorials/")
soup = BeautifulSoup(req.text,'lxml')

content = soup.find("div", class_="post-9")

f = open("first_lesson.html","w")
f.write(content.prettify().encode('utf-8'))
f.close()

我在文件夹中找到了 first_lesson.html 文件。问题是,当我打开 html 文件检查结果时,到处都有奇怪的符号(尝试运行代码并查看)。

我添加了 .encode('utf-8') 因为否则我会收到错误:

UnicodeEncodeError: 'ascii' codec can't encode character u'\u2014' in position 155: ordinal not in range(128)

如何消除那些奇怪的符号?什么是正确的编码?而且,如果我将来遇到类似的问题,我怎么知道什么是正确的编码?

更新:我没有使用“utf-8”编码,而是使用“windows-1252”编码,并且它有效。但是了解如何正确编码的最佳策略是什么?因为我不认为尝试这个尝试那个是好的

最佳答案

在 python2 中使用请求你应该使用.content要让请求处理编码,您可以使用 io.open写入文件:

import requests
from bs4 import BeautifulSoup
import io


req = requests.get("http://www.learncpp.com/cpp-tutorial/01-introduction-to-these-tutorials/")
soup = BeautifulSoup(req.content, 'lxml')
content = soup.find("div", class_="post-9")

with io.open("first_lesson.html", "w") as f:
f.write(soup.prettify())

如果您确实想指定编码,则 prettify 需要一个编码参数 soup.prettify(encoding=...) ,还有编码属性:

enc = req.encoding

您可以尝试用 cgi.parse_headers 解析 header :

import cgi

enc = cgi.parse_header(req.headers.get('content-type', ""))[1]["charset"]

或者尝试安装并使用chardet模块:

import chardet

enc = chardet.detect(req.content)

您还应该意识到,许多编码可能运行时没有错误,但最终会在文件中产生垃圾。字符集设置为 utf-8,您可以在返回的 header 中看到它,如果您查看源代码,您可以看到 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> .

关于python - 如何知道什么是正确的编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34975507/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com