UnicodeEncodeError: 'ascii'编解码器无法编码字符?

4

我正在尝试用正则表达式处理大量随机的html字符串,但我的Python 2.6脚本却产生了错误:

UnicodeEncodeError: 'ascii'编解码器不能编码此字符

我追踪到了这个单词末尾的商标上标符号:Protection™——虽然我不需要捕获非ascii字符,但它很麻烦,而且我预计在未来会遇到更多类似问题。

有没有一个处理非ascii字符的模块?或者,在Python中处理/转义非ascii字符的最佳方法是什么?

谢谢! 完整错误信息:

E
======================================================================
ERROR: test_untitled (__main__.Untitled)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Python26\Test2.py", line 26, in test_untitled
    ofile.write(Test + '\n')
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2122' in position 1005: ordinal not in range(128)

完整脚本:

from selenium import selenium
import unittest, time, re, csv, logging

class Untitled(unittest.TestCase):
    def setUp(self):
        self.verificationErrors = []
        self.selenium = selenium("localhost", 4444, "*firefox", "http://www.BaseDomain.com/")
        self.selenium.start()
        self.selenium.set_timeout("90000")

    def test_untitled(self):
        sel = self.selenium
        spamReader = csv.reader(open('SubDomainList.csv', 'rb'))
        for row in spamReader:
            sel.open(row[0])
            time.sleep(10)
            Test = sel.get_text("//html/body/div/table/tbody/tr/td/form/div/table/tbody/tr[7]/td")
            Test = Test.replace(",","")
            Test = Test.replace("\n", "")
            ofile = open('TestOut.csv', 'ab')
            ofile.write(Test + '\n')
            ofile.close()

    def tearDown(self):
        self.selenium.stop()
        self.assertEqual([], self.verificationErrors)

if __name__ == "__main__":
    unittest.main()

1个回答

6
你的另一个问题已经被完整地重复了,链接在这里:https://dev59.com/Z3I-5IYBdhLWcg3w0cOG(尽管你终于开始展示代码了,哇!)。答案仍然相同:不要使用
        ofile.write(Test + '\n')


        ofile.write(Test.encode('utf8') + '\n')

为什么你一直重复这个问题,顺便问一下?!

我想这应该是我一开始应该问的问题。这样你就可以更清楚地回答了。而你确实做到了。谢谢Alex! - KenBurnsFan1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接