【问题标题】:Encode UTF-8 for list为列表编码 UTF-8
【发布时间】:2015-08-06 08:45:42
【问题描述】:

我正在使用 selenium 从 javascript 对象中检索列表。

search_reply = driver.find_element_by_class_name("ac_results")

尝试写入 csv 时,我收到此错误:

Traceback (most recent call last):
  File "insref_lookup15.py", line 54, in <module>
    wr_insref.writerow(instrument_name)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 22: ordinal not in range(128)

我已尝试将 .encode("utf-8") 放在两者上:

search_reply = driver.find_element_by_class_name("ac_results").encode("utf-8")

wr_insref.writerow(instrument_name).encode("utf-8")

但我只是收到消息

AttributeError: 'xxx' object has no attribute 'encode'

【问题讨论】:

  • driver.find_element_by_class_name 返回什么?是清单吗?是一门课吗?我可以推断出它肯定不是字符串。
  • @Winterflags: 在那个列表中只有字符串对象?大概打印它会给出类似[u'foo', u'bar',...]
  • @MartijnPieters 是的,我得到 [u'foo', u'bar',...]。

标签: python python-2.7 encoding utf-8


【解决方案1】:

您需要对列表中的元素进行编码

wr_insref.writerow([v.encode('utf8') for v in instrument_name])

csv 模块文档中有一个 Examples section 更详细地介绍了编写 Unicode 对象,包括用于自动处理此问题的实用程序类。

【讨论】:

    猜你喜欢
    • 2013-06-02
    • 2016-01-26
    • 2019-03-31
    • 1970-01-01
    • 2011-10-30
    • 2012-04-24
    • 2015-11-08
    • 2012-11-07
    • 1970-01-01
    相关资源
    最近更新 更多