【问题标题】:Python 'latin-1' codec can't encode character - How to ignore characters?Python 'latin-1' 编解码器无法编码字符 - 如何忽略字符?
【发布时间】:2019-02-15 16:30:20
【问题描述】:

这是我的代码的要点。它试图从旧网站获取一些文本。这不是我的,所以我无法更改来源。

from bs4 import BeautifulSoup
import requests

response = requests.get("https://mattgemmell.com/network-link-conditioner-in-lion/")
data = response.text
soup = BeautifulSoup(data, 'lxml')
article = soup.find_all('article')[0]
text = article.find_all('p')[1].text 
print(text)

给出这个:

'如果您是使用网络的 Mac 或 iOS 应用程序的开发人员,则在 Mac OS X 10.7 开发人员工具中的一项新功能 â\x80\x9cLionâ\x80\x9d(阅读我在《卫报》上对它的评论)对你很有用。这篇简短的文章描述了它的工作原理。'

我可以用它来转换像â\x80\x99这样的部分:

converted_text = bytes(text, 'latin-1').decode('utf-8')

确实有效。

但如果你得到文本的不同部分:

text = article.find_all('p')[8].text 

给我:

'\n← 在 Lion 上查找文本中的模式\n在 OS X Lion 上使用空格 →\n'

使用bytes(text, 'latin-1') 给了我:

“latin-1”编解码器无法在位置 1 编码字符“\u2190”:序数不在范围内(256)

我猜是箭?我怎样才能让它自动忽略和丢弃所有非拉丁字符。

任何想法都会很有帮助!

【问题讨论】:

  • 你为什么要编码成latin-1,然后用utf-8解码?

标签: python web-scraping beautifulsoup html-parsing


【解决方案1】:

您不想忽略这些字符。它们是您收到的数据已使用错误的字符编码解码的症状。在您的情况下,requests 错误地猜测编码是latin-1。真正的编码是utf-8,并在HTML 响应中的<meta> 标记中指定。 requests 是一个使用 HTTP 的库,它不了解 HTML。由于Content-Type 标头没有指定编码requests 只好猜测编码。然而,BeautifulSoup 是一个用于处理 HTML 的库,它非常擅长检测编码。因此,您希望从响应中获取原始字节并将其传递给BeautifulSoup。即。

from bs4 import BeautifulSoup
import requests

response = requests.get("https://mattgemmell.com/network-link-conditioner-in-lion/")
data = response.content # we now get `content` rather than `text`
assert type(data) is bytes
soup = BeautifulSoup(data, 'lxml')
article = soup.find_all('article')[0]
text = article.find_all('p')[1].text 
print(text)

assert type(text) is str
assert 'Mac OS X 10.7 “Lion”' in text

【讨论】:

  • 我已经添加了我的问题的完整上下文,所以我可以确保我在正确的位置应用了修复。我的理解是,beautiful soup 应该为您找到正确的编码,并且在大多数情况下都有效,但在我试图抓取的所有网页上除外。
  • @Frankie 进行了编辑。这是一个简单的改变。希望对您有所帮助。
  • 感谢您提供额外的解释和上下文,以确保我做对了。
【解决方案2】:

使用bytes 的第三个参数告诉它如何处理错误:

converted_text = bytes(text, 'latin-1', 'ignore')
                                         ^^^^^^

你会失去箭头,但除此之外一切都完好无损:

>>> text = '\n← Find Patterns in text on Lion\nUsing Spaces on OS X Lion →\n'
>>> converted_text = bytes(text, 'latin-1', 'ignore')
>>> converted_text
'\n Find Patterns in text on Lion\nUsing Spaces on OS X Lion \n'

以下是有关文档参数的更多信息 - https://docs.python.org/3.3/howto/unicode.html

errors 参数指定当输入字符串不能根据编码规则转换时的响应。此参数的合法值为 'strict'(引发 UnicodeDecodeError 异常)、'replace'(使用 U+FFFD、REPLACEMENT CHARACTER)或 'ignore'(仅将字符排除在 Unicode 结果之外)。

【讨论】:

  • 这也很有帮助。
猜你喜欢
  • 2012-01-07
  • 2011-04-25
  • 1970-01-01
  • 1970-01-01
  • 2018-12-11
  • 2019-12-09
  • 1970-01-01
  • 2019-12-09
相关资源
最近更新 更多