Python 3写入TXT出现'gbk' codec can't encode错误的解决办法
in 各种出错 with 0 comment
Python 3写入TXT出现'gbk' codec can't encode错误的解决办法
in 各种出错 with 0 comment

1.png

在Windows上用Python 3 写一个爬虫,但是读取网页内容并且把网页内容写进txt文件的时候,出现了这个异常

UnicodeEncodeError: 'gbk' codec can't encode character '\u10da' in position 135026: illegal multibyte sequence

问题的原因在于Python 3里面字符串的默认编码是Unicode的
爬取的网页内容,是储存在字符串变量里。
而使用代码创建TXT时,Windows下面新建的文本文件默认的编码是gbk(Windows简体中文版的系统默认编码就是gbk)
2.png
当把从网页上读取的内容写到文本文件里去的时候,意味着把一个unicode的字符序列写入到一个编码是gbk的文件
故报错,解决方法就是在打开该文件的时候,指定文件的编码,让它以指定的编码打开:
}))_6B@H~CAB2M)1V0FCK2D.png

解决

你不是程序员,你只是让简单的事情自动化。


Deprecated: array_key_exists(): Using array_key_exists() on objects is deprecated. Use isset() or property_exists() instead in /www/wwwroot/ae.lcean.com/usr/themes/pinghsu-master/post.php on line 109

Deprecated: array_key_exists(): Using array_key_exists() on objects is deprecated. Use isset() or property_exists() instead in /www/wwwroot/ae.lcean.com/usr/themes/pinghsu-master/post.php on line 111

Deprecated: array_key_exists(): Using array_key_exists() on objects is deprecated. Use isset() or property_exists() instead in /www/wwwroot/ae.lcean.com/usr/themes/pinghsu-master/post.php on line 113

Deprecated: array_key_exists(): Using array_key_exists() on objects is deprecated. Use isset() or property_exists() instead in /www/wwwroot/ae.lcean.com/usr/themes/pinghsu-master/post.php on line 115

Deprecated: array_key_exists(): Using array_key_exists() on objects is deprecated. Use isset() or property_exists() instead in /www/wwwroot/ae.lcean.com/usr/themes/pinghsu-master/post.php on line 117

Deprecated: array_key_exists(): Using array_key_exists() on objects is deprecated. Use isset() or property_exists() instead in /www/wwwroot/ae.lcean.com/usr/themes/pinghsu-master/post.php on line 119

Deprecated: array_key_exists(): Using array_key_exists() on objects is deprecated. Use isset() or property_exists() instead in /www/wwwroot/ae.lcean.com/usr/themes/pinghsu-master/post.php on line 121

Deprecated: array_key_exists(): Using array_key_exists() on objects is deprecated. Use isset() or property_exists() instead in /www/wwwroot/ae.lcean.com/usr/themes/pinghsu-master/post.php on line 123

Deprecated: array_key_exists(): Using array_key_exists() on objects is deprecated. Use isset() or property_exists() instead in /www/wwwroot/ae.lcean.com/usr/themes/pinghsu-master/post.php on line 125

Deprecated: array_key_exists(): Using array_key_exists() on objects is deprecated. Use isset() or property_exists() instead in /www/wwwroot/ae.lcean.com/usr/themes/pinghsu-master/post.php on line 127
Responses