为什么我会得到'UnicodeEncodeError'?

时间:2013-07-01 17:25:25

标签: python

我有这个代码(警告:仅限成人的网址内容!)

# Encoding: UTF-8

import re
import requests
# import chardet

html = requests.get('http://klonedaset.org/news.php?sid=51854&bn=luRsF2aAa6eV63nU71Jm&ad=0&ref=&pt=&cookie=null&cls=null').text
text = re.findall('target=_blank id=.*?>(.*?)</a>', html)[0]
# print chardet.detect(text) return this "{'confidence': 0.9599621544520228, 'encoding': 'windows-1251'}"

open('file12.txt', 'a').write(text)

我在最后一行(我在文件中写的地方)得到了这个错误

UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128) 

我正在尝试这样做

html = html.decode(windows-1251').encode('UTF-8')

但它不起作用。我必须用UTF-8写入文件!

1 个答案:

答案 0 :(得分:-1)

open('file12.txt', 'ab').write(text)

您需要将其打开以进行二进制编写。更好用:

import codecs
file = codecs.open('file12.txt', mode="wb", encoding="utf-8")