py文件输出html内容显示编码问题及解决方案

本文介绍了一种在Python中解决打印HTML内容时出现编码错误的方法。通过将HTML内容从'utf-8'编码转换为'gbk'编码,再进行打印,可以避免因编码不匹配导致的问题。

问题描述: 在py文件中输出和html内容,但是显示编码错误

代码如下

#主页面和tr进行拼接
html ="""
<!DOCTYPE html>
<html lang="en">
<head>
	<title>index</title>
</head>
<body>
	<center>
		<table>

			<tr>
				<!--<td>id</td>-->
				<td>姓名</td>
				<td>班级</td>
				<td>电话</td>
				

			</tr>
			{}

		</table>
	</center>
</body>
</html>

""".format(tr)
print(html)

运行结果:

 原因分析:网页的数据应该是'utf-8'编码,这个可以在网页的head上面看得到,出问题的是在print()这儿,对于print()这个函数,他需要把内容转化为'gbk'编码才能显示出来. 

解决方案:在print(html)代码前添加如下代码

html =  html.encode('GBK','ignore').decode('GBK') 

正确代码:

#主页面和tr进行拼接
html ="""
<!DOCTYPE html>
<html lang="en">
<head>
	<title>index</title>
</head>
<body>
	<center>
		<table>

			<tr>
				<!--<td>id</td>-->
				<td>姓名</td>
				<td>班级</td>
				<td>电话</td>
				

			</tr>
			{}

		</table>
	</center>
</body>
</html>

""".format(tr)
html =  html.encode('GBK','ignore').decode('GBK') 
print(html)

实行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值