【问题标题】:How to solve unicode error from exporting to csv file (python)如何解决导出到 csv 文件时出现的 unicode 错误(python)
【发布时间】:2019-02-14 02:27:05
【问题描述】:

我正在尝试使用 python 从网络抓取中导出文本。然而,结果表明:

> UnicodeEncodeError Traceback (most recent call last) in () 71
> 'ranking_title': ranking_title, ---> 72 'ranking_category':
> ranking_category}) 73
> 
> ~\Anaconda3\lib\csv.py in writerow(self, rowdict) 154 def
> writerow(self, rowdict): --> 155 return
> self.writer.writerow(self._dict_to_list(rowdict)) 156
> 
> ~\Anaconda3\lib\encodings\cp1252.py in encode(self, input, final) 18
> def encode(self, input, final=False): ---> 19 return
> codecs.charmap_encode(input,self.errors,encoding_table)[0] 20
> 
> UnicodeEncodeError: 'charmap' codec can't encode characters in
> position 299-309: character maps to

我可能犯了什么错误?我可以将我刮过一次的文本导出到 CSV 文件中,但是当我改天尝试时,它是错误的。

附言。我已经在工作簿的开头导入了 Beautifulsoup 和 csv。

【问题讨论】:

  • 您为什么使用代码页 1252 而不是 UTF-8?
  • @PM2Ring 我不知道代码页 1252 是如何搞砸的。我认为它来自默认设置。怎么改成UTF-8?
  • 看起来您的 HTML 包含 cp1252 不支持的 Unicode 字符。保留这些字符的最佳方法是使用旨在处理 Unicode 的编码,例如 UTF-8。在 Linux 上,修改环境以使用 UTF-8 作为终端中的默认编码非常容易。我相信这在 Windows 上有点棘手,但 Stack Overflow 上有描述如何做到这一点的答案。
  • 我试试,非常感谢。
  • 只显示了一个选项here。可能有更好的方法,如果您总是从 IDE 运行代码,那么它应该为您提供一种选择编码的方法。但我与 Windows 的接触不多,所以对于这类事情我无法提供太多帮助。

标签: python csv beautifulsoup jupyter-notebook export-to-csv


【解决方案1】:

添加用于检查 Unicode 的 try-catch 块:

try:
    to_unicode = unicode
except NameError:
    to_unicode = str

# requests the URL
site = requests.get('specify URL')

# decodes the string using the codec registered for encoding.

data = site.content.decode('utf-8')

# use Beautiful Soup for scraping
Soup = BS(data, 'lxml')

最后,在写入文件时,请确保以 Unicode 格式写入:

file.write(to_unicode(data))

我希望这会有所帮助。

【讨论】:

  • 谢谢您,但仍然导致错误。我将“try and except”放在url请求的上方并将“file.write”放在Writerow下方是否正确?
猜你喜欢
  • 2013-12-19
  • 1970-01-01
  • 1970-01-01
  • 2018-07-07
  • 2018-01-26
  • 1970-01-01
  • 1970-01-01
  • 2012-04-18
  • 2018-02-18
相关资源
最近更新 更多