Python3.x + Apache2.x 輸出html中文亂碼問題
以下內容僅供參考使用,結合自身情況選擇
代碼示範:
#!H:/worksoft/Python38/python.exe #Python安裝路徑
# coding:utf-8 #字符編碼
print("Content-type:text/html;\n")
print('<!DOCTYPE html>')
print('<head>')
print('<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />')
print('<title>我的第一個 CGI 程序!</title>')
print('</head>')
print('<body>')
print('<h2>Hello Word! 這是我的第一CGI程序</h2>')
print('</body>')
print('</html>')
通常在這個時候我們會以爲是正常的,當你運行訪問的時候會發現出現亂碼了,那麼解決方案來了:
方案一:去掉 <meta http-equiv=“Content-Type” content=“text/html; charset=UTF-8” />。
方案二:將charset=UTF-8修改爲charset=GB2312。
方案三:引入sys模塊,使用sys.stdout = codecs.getwriter(‘utf-8’)(sys.stdout.buffer)。
方案四:修改Appache/conf/httpd.conf文件中AddDefaultCharset狀態on或者字符utf-8,沒有則添加。(不推薦)
語法:AddDefaultCharset On|Off|charset ,默認值 AddDefaultCharset Off。
說明:當應答內容是text/plain或text/html時,在HTTP應答頭中加入的默認字符集。