【问题标题】:python reading unicode characters from htmlpython从html读取unicode字符
【发布时间】:2012-05-22 06:03:24
【问题描述】:

我有这个脚本,它从网页中读取文本:

page = urllib2.urlopen(url).read()
soup = BeautifulSoup(page);
paragraphs = soup.findAll('p');

for p in paragraphs:
    content = content+p.text+" ";

在网页中我有这个字符串:

Möddinghofe

我的脚本是这样写的:

Möddinghofe

我怎样才能按原样阅读它?

【问题讨论】:

标签: python


【解决方案1】:

希望对你有帮助

from BeautifulSoup import BeautifulStoneSoup
import cgi

def HTMLEntitiesToUnicode(text):
    """Converts HTML entities to unicode.  For example '&' becomes '&'."""
    text = unicode(BeautifulStoneSoup(text, convertEntities=BeautifulStoneSoup.ALL_ENTITIES))
    return text

def unicodeToHTMLEntities(text):
    """Converts unicode to HTML entities.  For example '&' becomes '&'."""
    text = cgi.escape(text).encode('ascii', 'xmlcharrefreplace')
    return text

text = "&, ®, <, >, ¢, £, ¥, €, §, ©"

uni = HTMLEntitiesToUnicode(text)
htmlent = unicodeToHTMLEntities(uni)

print uni
print htmlent
# &, ®, <, >, ¢, £, ¥, €, §, ©
# &amp;, &#174;, &lt;, &gt;, &#162;, &#163;, &#165;, &#8364;, &#167;, &#169;

参考:Convert HTML entities to Unicode and vice versa

【讨论】:

    【解决方案2】:

    我建议您查看 BeautifulSoup 文档的 encoding 部分。

    【讨论】:

      猜你喜欢
      • 2015-09-25
      • 2016-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多