python爬虫问题01--‘gbk‘,utf-8

"在Python爬虫过程中遇到编码问题,保存网页内容时出现`UnicodeEncodeError`,原因是Windows默认以GBK编码打开文件。解决方案是在`with open()`语句中添加`encoding="utf-8"`参数,确保以UTF-8编码写入文件,从而避免编码冲突。"
摘要由CSDN通过智能技术生成

1. 问题

被爬虫的网页是"UTF-8"格式的编码,但是我在保存内容时

from urllib.request import urlopen

def get_url():
    url = 'https://www.hao123.com/'
    resp = urlopen(url)
    with open('baidu.html', mode='w') as file:
        content = resp.read()
        # print(f)
        # file.write(f)
        file.write(content.decode("UTF-8"))
        print('file is done!!')


if __name__ == '__main__':
    get_url()

出现了下面的错误

UnicodeEncodeError: 'gbk' codec can't encode character '\u2022' in position 252532: illegal multibyte sequence

2. 问题及解决方案

原因是windows默认打开文件的时候采用的是‘gbk'编码,这里我们修改其编码的方式为’UTF-8‘即可

with open('baidu.html', mode='w', encoding="utf-8") as file:

在打开的这行函数加了encoding="utf-8"

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值