正则表达式 – UnicodeEncodeError:’ascii’编解码器无法编码字符?

前端之家收集整理的这篇文章主要介绍了正则表达式 – UnicodeEncodeError:’ascii’编解码器无法编码字符?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图通过正则表达式传递大量的随机html字符串,我的Python 2.6脚本对此感到窒息:

UnicodeEncodeError:’ascii’编解码器无法编码字符

我在这个词的末尾追溯到一个商标上标:Protection™ – 我不需要捕获非ascii的东西,但这是一个麻烦,我希望将来会更多地遇到它.

是否有处理非ascii字符的模块?或者,在python中处理/转义非ascii内容的最佳方法是什么?

谢谢!
完整错误

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

完整脚本:

  1. from selenium import selenium
  2. import unittest,time,re,csv,logging
  3.  
  4. class Untitled(unittest.TestCase):
  5. def setUp(self):
  6. self.verificationErrors = []
  7. self.selenium = selenium("localhost",4444,"*firefox","http://www.BaseDomain.com/")
  8. self.selenium.start()
  9. self.selenium.set_timeout("90000")
  10.  
  11. def test_untitled(self):
  12. sel = self.selenium
  13. spamReader = csv.reader(open('SubDomainList.csv','rb'))
  14. for row in spamReader:
  15. sel.open(row[0])
  16. time.sleep(10)
  17. Test = sel.get_text("//html/body/div/table/tbody/tr/td/form/div/table/tbody/tr[7]/td")
  18. Test = Test.replace(",","")
  19. Test = Test.replace("\n","")
  20. ofile = open('TestOut.csv','ab')
  21. ofile.write(Test + '\n')
  22. ofile.close()
  23.  
  24. def tearDown(self):
  25. self.selenium.stop()
  26. self.assertEqual([],self.verificationErrors)
  27.  
  28. if __name__ == "__main__":
  29. unittest.main()
你的另一个问题 here的总重复次数(虽然在这里你最终设法从头开始向我们展示CODE!哇! – ).答案仍然相同:而不是
  1. ofile.write(Test + '\n')

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

为什么你一直在重复这个Q,BTW?!

猜你在找的正则表达式相关文章