【问题标题】:Python webpage source read with special charactersPython网页源码读取特殊字符
【发布时间】:2013-08-19 05:44:37
【问题描述】:

我正在从网页读取页面源,然后从该源解析一个值。 在那里我遇到了特殊字符的问题。

在我的 python 控制器文件 iam 中使用 # -*- coding: utf-8 -*-。 但我正在阅读使用charset=iso-8859-1

的网页源

所以当我在没有指定任何编码的情况下阅读页面内容时,它会抛出错误UnicodeDecodeError: 'utf8' codec can't decode byte 0xfc in position 133: invalid start byte

当我使用string.decode("iso-8859-1").encode("utf-8") 时,它正在解析数据而没有任何错误。但它将值显示为“F\u00fcnke”而不是“Fünke”。

请告诉我如何解决这个问题。 我将不胜感激任何建议。

【问题讨论】:

  • 尝试打印u"F\u00fcnke"
  • Python 2 还是 3?
  • Python 2.7。并尝试 unicode() 它显示相同。

标签: python webpage urlencode


【解决方案1】:

编码肯定是 Python3 中的 PITA(在某些情况下也是 2)。 尝试检查这些链接,它们可能会对您有所帮助:

Python - Encoding string - Swedish Letters
Python3 - ascii/utf-8/iso-8859-1 can't decode byte 0xe5 (Swedish characters)

http://docs.python.org/2/library/codecs.html

另外,"So when I read the page content without specifying any encoding" 的代码会很好我最好的猜测是你的控制台不使用 utf-8(例如,windows .. 你的 # -*- coding: utf-8 -*- 只告诉 Python 要在其中找到什么类型的字符源代码,而不是代码将要解析或分析的实际数据。 比如我写:

# -*- coding: iso-8859-1 -*-
import time
# Här skriver jag ut tiden (Translation: Here, i print out the time)
print(time.strftime('%H:%m:%s'))

【讨论】:

  • 无缘无故地投反对票,真正有建设性的(如果我错了,至少指出 ffs)-.-
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-19
  • 2013-06-07
  • 1970-01-01
  • 2017-08-27
  • 1970-01-01
  • 1970-01-01
  • 2012-12-09
相关资源
最近更新 更多