栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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"

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/657656.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号