爬虫爬取网页错误:UnicodeEncodeError: 'gbk' codec can't encode character '\xe7' in position 318

在爬虫爬取网页的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:

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值