【问题标题】:BeautifulSoup changes HTMLBeautifulSoup 更改 HTML
【发布时间】:2014-06-21 21:17:14
【问题描述】:

我注意到,当我使用 Beautiful Soup 从 Web 获取 HTML 时,它会发生某种变化。这是我用来获取它的代码:

from bs4 import BeautifulSoup
import requests
url ="http://www.basketnews.lt/lygos/59-nacionaline-krepsinio-asociacija/2013/naujienos.html"
r = requests.get(url)
soup = BeautifulSoup(r.text)
print soup

这是原始 HTML 的一部分:

<a href="/news-73149-valanciunui-ir-raptors-sezonas-baigtas-foto-statistika.html">Valančiūnui ir Raptors sezonas baigtas <span class="title_description">(foto, statistika)</span></a>`

这是与 Beautiful Soup 相同的 HTML 部分:

<a href="/news-73149-valanciunui-ir-raptors-sezonas-baigtas-foto-statistika.html">ValanÄiÅ«nui ir âRaptorsâ sezonas baigtas <span class="title_description">(foto, statistika)</span></a>

您会看到我正在解析的 HTML 中的文本是如何混乱的。问题出在哪里?

【问题讨论】:

  • 我认为您粘贴的代码中还有一些额外的`

标签: python beautifulsoup python-requests


【解决方案1】:

您正在使用r.text,这意味着requests 将使用默认编码;但是它弄错了:

>>> r = requests.get(url)
>>> r.headers['content-type']
'text/html'
>>> r.encoding
'ISO-8859-1'
>>> r.apparent_encoding
'utf-8'

ISO-8859-1(拉丁语 1)是 HTTP 1.1 default encoding for text/ responses

使用检测算法时,会找到 UTF-8。

您不应该使用r.text,而是使用r.content,将其留给BeautifulSoup 进行检测:

soup = BeautifulSoup(r.content)

现在它可以正常工作了:

>>> soup = BeautifulSoup(r.content)
>>> soup.find('a', href='/news-73149-valanciunui-ir-raptors-sezonas-baigtas-foto-statistika.html')
<a href="/news-73149-valanciunui-ir-raptors-sezonas-baigtas-foto-statistika.html">Valančiūnui ir „Raptors“ sezonas baigtas <span class="title_description">(foto, statistika)</span></a>
>>> print soup.find('a', href='/news-73149-valanciunui-ir-raptors-sezonas-baigtas-foto-statistika.html').text
Valančiūnui ir „Raptors“ sezonas baigtas (foto, statistika)

BeautifulSoup 使用自动检测,但在这种情况下,它会在页面中找到具有正确编码的&lt;meta&gt; 标头

>>> soup.find('meta', {'http-equiv': 'content-type'})
<meta content="text/html; charset=utf-8" http-equiv="content-type"/>

【讨论】:

  • 为什么requests 假定它应该使用'ISO-8859-1'?我认为OP必须手动指定它。
  • @cubuspl42:它是text/ mimetypes 的默认编码。
  • soup = BeautifulSoup(r.text.encode("latin-1")) 也不行吗?
  • @cubuspl42:我添加了对 HTTP 1.1 RFC 的引用。
  • @PadraicCunningham:它会产生相同的输出,是的,但为什么要解码,然后重新编码?
猜你喜欢
  • 2018-07-21
  • 1970-01-01
  • 1970-01-01
  • 2019-10-19
  • 2021-03-20
  • 2016-12-30
  • 2015-10-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多