【问题标题】:Ignore Unicode Error忽略 Unicode 错误
【发布时间】:2011-09-28 19:33:37
【问题描述】:

当我在一堆 URL 上运行循环以查找这些页面上的所有链接(在某些 Div 中)时,我得到了这个错误:

Traceback (most recent call last):
File "file_location", line 38, in <module>
out.writerow(tag['href'])
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2026' in position 0: ordinal not in range(128)

我写的与这个错误相关的代码是:

out  = csv.writer(open("file_location", "ab"), delimiter=";")
for tag in soup_3.findAll('a', href=True):   
    out.writerow(tag['href'])

有没有办法解决这个问题,可能使用 if 语句来忽略任何有 Unicode 错误的 URL?

提前感谢您的帮助。

【问题讨论】:

    标签: python unicode csv ascii


    【解决方案1】:

    您可以将 writerow 方法调用包装在 try 中并捕获异常以忽略它:

    for tag in soup_3.findAll('a', href=True):
        try:
            out.writerow(tag['href'])
        except UnicodeEncodeError:
            pass
    

    但您几乎肯定想为您的 CSV 文件选择除 ASCII 以外的编码(除非您有充分的理由使用其他编码,否则为 utf-8),并使用 codecs.open() 而不是内置的 @ 打开它987654324@.

    【讨论】:

    • 非常感谢我使用了 try: 并且效果很好。您如何更改编码以及为什么要这样做?请原谅这个基本问题,但我对编程很陌生。
    • 几乎总是,您不想丢弃数据,因为它碰巧使用了非 ASCII 字符。如果您使用open("file_location", "ab","utf-8") 打开文件,而不是抛出UnicodeEncodeErrorout.write 将写入它从网站读取的实际数据,这在 99% 的情况下是您真正想要的。
    • 啊,这会有所帮助,当我将“utf-8”添加到打开的当前行的末尾时,我收到错误:TypeError: an integer is required 我应该只使用 open(" file_location”,“ab”,“utf-8”),如果是这样,我该如何引入 csv.writer 以便它可以在“try:”部分中使用。再次感谢您的帮助
    • 哎呀;你想要codecs.open(首先导入codecs),而不仅仅是open,正如我在上面的答案中所说的,但不是在示例评论中。
    猜你喜欢
    • 1970-01-01
    • 2014-12-06
    • 2018-05-04
    • 1970-01-01
    • 1970-01-01
    • 2012-05-10
    • 2015-12-29
    • 2014-07-30
    • 2014-02-13
    相关资源
    最近更新 更多