gpt4 book ai didi

网站的Python正确编码(Beautiful Soup)

转载 作者:太空狗 更新时间:2023-10-29 21:12:36 31 4
gpt4 key购买 nike

我正在尝试加载 html 页面并输出文本,即使我正确获取网页,BeautifulSoup 以某种方式破坏了编码。

来源:

# -*- coding: utf-8 -*-
import requests
from BeautifulSoup import BeautifulSoup

url = "http://www.columbia.edu/~fdc/utf8/"
r = requests.get(url)

encodedText = r.text.encode("utf-8")
soup = BeautifulSoup(encodedText)
text = str(soup.findAll(text=True))
print text.decode("utf-8")

摘录输出:

...Odenw\xc3\xa4lderisch...

这应该是Odenwälderisch

最佳答案

你犯了两个错误;您错误地处理了编码,并且将结果列表视为可以安全地转换为字符串而不会丢失信息的内容。

首先,不要使用response.text !这不是 BeautifulSoup 的错,您正在重新编码 Mojibake . requests库将默认为 text/* 的 Latin-1 编码服务器未明确指定编码时的内容类型,因为 HTTP 标准规定这是默认值。

参见 Encoding section of the Advanced documentation :

The only time Requests will not do this is if no explicit charset is present in the HTTP headers and the Content-Type header contains text. In this situation, RFC 2616 specifies that the default charset must be ISO-8859-1. Requests follows the specification in this case. If you require a different encoding, you can manually set the Response.encoding property, or use the raw Response.content.

大胆强调我的。

传入response.content原始数据:

soup = BeautifulSoup(r.content)

我看到您正在使用 BeautifulSoup 3。您确实想升级到 BeautifulSoup 4;版本 3 已于 2012 年停产,并且包含多个错误。安装 beautifulsoup4 project ,并使用 from bs4 import BeautifulSoup .

BeautifulSoup 4 通常可以很好地找出解析时使用的正确编码,无论是来自 HTML <meta>提供的字节的标记或统计分析。如果服务器确实提供了字符集,您仍然可以将其从响应中传递到 BeautifulSoup,但如果 requests 则先进行测试使用默认值:

encoding = r.encoding if 'charset' in r.headers.get('content-type', '').lower() else None
parser = 'html.parser' # or lxml or html5lib
soup = BeautifulSoup(r.content, parser, from_encoding=encoding)

最后但同样重要的是,使用 BeautifulSoup 4,您可以使用 soup.get_text() 从页面中提取所有文本:

text = soup.get_text()
print text

您要将结果列表(soup.findAll() 的返回值)转换为字符串。这永远行不通,因为 Python 中的容器使用 repr()在列表中的每个元素上生成一个调试字符串,对于字符串,这意味着您可以获得任何非可打印 ASCII 字符的转义序列。

关于网站的Python正确编码(Beautiful Soup),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36833357/

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