0
我想解析一個HTML頁面與python3的HTMLParser。UnicodeEncodeError解析HTML時
編輯:
嘗試打印使用的字符:
print ('\u25bc') #Prints the '▼' character
拋出UnicodeEncodeError。
的代碼是文檔樣品中所提供的一個:
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
print("Start tag:", tag)
for attr in attrs:
print(" attr:", attr)
def handle_endtag(self, tag):
print("End tag :", tag)
def handle_data(self, data):
print("Data :", data)
def handle_comment(self, data):
print("Comment :", data)
def handle_entityref(self, name):
c = chr(name2codepoint[name])
print("Named ent:", c)
def handle_charref(self, name):
if name.startswith('x'):
c = chr(int(name[1:], 16))
else:
c = chr(int(name))
print("Num ent :", c)
def handle_decl(self, data):
print("Decl :", data)
和進給HTML文檔(UTF-8字符串),我發現了錯誤時:
UnicodeExcodeError
'ascii' codec can't encode character '\u25bc' in position 0: ordinal not in range(128)
來自parser getpos()方法的違規行是:
# |-- Parser stopped here.
<li><a href="#" class="dir">▼ Community</a>
將讀取的字節正確解碼爲UTF-8字符串,然後將其饋送到解析器的feed()方法,該解析器出於某種原因試圖將其編碼爲ASCII。
系統區域默認設置爲「POSIX」,但在本地使用
export LANG=en_US.UTF-8
我該如何解決這個問題設置爲en_US.UTF-8?
如果你需要重定向到一個文件或管道,那麼你可以使用:'PYTHONIOENCODING = utf-8 python3 -c'print(「\ u25bc」)'| cat' – jfs