2013-07-01 21 views
-1

我有這樣的代碼(警告:對URL內容僅供大人!)爲什麼我會得到'UnicodeEncodeError'?

# 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
open('file12.txt', 'ab').write(text) 

您需要打開它進行二進制寫入。更好的使用:

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

此外,網址很奇怪,它會產生一個破損的頁面。 –

+0

meh ..我只是得到高風險的網站被鉻封鎖......但我想我會解決他看到的問題 –

+0

我不會阻止本網站或不,但你可以看到一個圖片和文本在Windows-1251 。另外,親愛的喬蘭,進入文件寫這樣的想法「Ñûíîñïîëüçîâàëëñÿïüÿíûìæåëàíèåììàòåðè!」 :( –

相關問題