エンコーディングで使用できない文字を文字実体参照に変換する方法。
htmlentitydefs.codepoint2nameを使うと、ユニコード文字のコードポイントをHTMLのエンティティ名に変換することができます。
from htmlentitydefs import codepoint2name
s = u'<html><body>©®</body></html>'
f = open('sjis.html', 'w')
for c in s:
try:
f.write(c.encode('shift_jis'))
except UnicodeError:
f.write('&%s;' % codepoint2name[ord(c)])
f.close()
出力結果
<html><body>©®</body></html>
htmlentitydefs.codepoint2nameを使えば、ファイルに指定したエンコーディングを使い、ブラウザでユニコード文字列を表示することが出来ます。