忽略Unicode错误

4 投票
1 回答
11596 浏览
提问于 2025-04-17 03:18

当我在一堆网址上运行一个循环,想要找到这些页面中某些

里的所有链接时,我遇到了这个错误:

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错误的网址?

提前感谢你的帮助。

1 个回答

6

你可以把写入行的方法调用放在一个try块里,这样如果出现错误就可以捕捉到并忽略它:

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

不过,你几乎肯定需要为你的CSV文件选择一种除了ASCII以外的编码(通常用utf-8,除非你有很好的理由使用其他编码),并且要用codecs.open()来打开文件,而不是直接用内置的open

撰写回答