在爬虫爬取网页的html源码写入文件
import requests
# 定义get请求
url = 'https://www.baidu.com/'
# 发起get请求
res = requests.get(url=url)
# 获取响应代码
code = res.status_code
print(code)
# 响应成功后把网页内容写入文件中
if code == 200:
with open('./test.html','w') as fp:
fp.write(res.text)
错误信息
UnicodeEncodeError: ‘gbk’ codec can’t encode character ‘\xe7’ in position 318: illegal multibyte sequence,中文翻译为UnicodeEncodeError:‘gbk’编解码器无法在位置318中编码字符’\ xe7’:非法的多字节序列
错误原因
python和html的编码不同,只需添加 encoding=‘utf-8’ 即可,即
with open(’./test.html’,‘w’) as fp:
with open(’./test.html’,‘w’,encoding=‘utf-8’) as fp: