Python将网页代码写入文件
原始代码
import requests
res = requests.get('https://localprod.pandateacher.com/python-manuscript/crawler-html/spider-men5.0.html')
code = res.text
file = open('abc.txt','w')
file.write(code)
file.close
产生报错
UnicodeEncodeError: 'gbk' codec can't encode character '\xa9' in position 3738: illegal multibyte sequence
解决方案
在windows系统中,新建的文本文件的默认编码是GBK,我们可以在程序中提前指定编码方式为通用的UTF-8.
file = open('abc.txt','w',encoding='utf-8') # 打开文件时候采用UTF-8编码