无论使用utf8编码,一些字符仍无法被识别

2024-06-16 14:37:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图用这样的新闻标题来搜集RSS:

<title>Photo of iceberg that is believed to have sunk Titanic sold at auction for £21,000 alongside &amp;#039;world&amp;#039;s most valuable biscuit&amp;#039;</title>

这就是我用靓汤刮的方法:

soup = BeautifulSoup(xml, 'xml')
start = soup.findAll('item')
for i in start:
    news, is_created = News.create_or_update(news_id,                                                  
    head_line=i.title.text.encode('utf-8').strip(),
    ...)

尽管如此,标题仍然是这样的:

Photo of iceberg that is believed to have sunk Titanic sold at auction for \xa321,000 alongside &#039;world&#039;s most valuable biscuit&#039;

将这些特殊字符转换成ASCII字符会更容易吗?你知道吗


Tags: oftoforthattitleishaveat
2条回答

对于您提供的示例,这对我很有用:

from bs4 import BeautifulSoup
import html

xml='<title>Photo of iceberg that is believed to have sunk Titanic sold at auction for £21,000 alongside &amp;#039;world&amp;#039;s most valuable biscuit&amp;#039;</title>'
soup = BeautifulSoup(xml, 'lxml')
print(html.unescape(soup.get_text()))

html.unescape处理HTML实体。如果Beautiful Soup没有正确处理磅符号,那么在创建BeautifulSoup对象时可能需要指定编码,例如

soup = BeautifulSoup(xml, "lxml", from_encoding='latin-1')

我终于相信找到了问题所在。上面这些字符是XML中转义的HTML。真是一团糟。如果你看《独立报》的RSS,大多数标题都会受到这样的影响。你知道吗

所以这不是UTF8的问题。在转换为UTF8之前,如何对标题中的任何html字符进行编码?你知道吗

head_line=i.title.text.encode('utf-8').strip(),

我用HTMLParser去掉标题,然后用UTF8编码来解决这个问题。马可的回答基本上是一样的。但是html库不适合我。你知道吗

head_line=HTMLParser.HTMLParser().unescape(i.title.text).encode('utf-8').strip(),

我不建议使用from_encoding='latin-1',因为它会导致其他问题。具有unescapingencode('utf-8')的解决方案足以将£解码为\xa3,这是合适的Unicode字符。你知道吗

相关问题 更多 >