zoukankan      html  css  js  c++  java
  • Python报错:UnicodeEncodeError 'gbk' codec can't encode character

    今天在使用Python文件处理写网络上爬取的文件的时候,遇到了错误:UnicodeEncodeError: ‘gbk’ codec can’t encode character ‘xa0’ in position … 这个问题。

    代码:

    import urllib.request  #等价与from urllib import request
    
    response = urllib.request.urlopen("http://www.baidu.com")
    print("查看response响应的类型",type(response))
    page_contect = response.read()
    with open(r'C:UsersPINPINDesktopdocx123.txt','w+') as f1:
        f1.write(page_contect.decode('utf-8'))

    出现错误:

    查看response响应的类型 <class 'http.client.HTTPResponse'>

    Traceback (most recent call last):

      File "C:UsersPINPINDesktopdocxurl_test.py", line 6, in <module>

        f1.write(page_contect.decode('utf-8'))

    UnicodeEncodeError: 'gbk' codec can't encode character 'xbb' in position 29150: illegal multibyte sequence

    出现问题的原因:在windows下面,新文件的默认编码是gbk,这样的话,python解释器会用gbk编码去解析我们的爬取的网络数据流,然而数据流此时已经是decode过的unicode编码,这样的话就会导致解析不了。

    解决的办法:改变目标文件的编码即可

    在打开文件时,指定文件编码格式:encode=’utf-8’

    with open(r'C:UsersPINPINDesktopdocx123.txt','w+',encode=’utf-8’) as f1:

    另外:网络数据流的编码,比如获取网页,网络数据流的编码就是网页的编码。需要使用decode解码成unicode编码。否则也会报错哦:TypeError: write() argument must be str, not bytes

    f1.write(page_contect.decode('utf-8'))所以在这里需要进行解码decode('utf-8')
  • 相关阅读:
    hdu6070
    hdu6059( Trie )
    hdu4757(可持久化 Trie )
    csu1216( Trie )
    hdu6058
    hdu6049
    hdu6052
    hdu6041
    hdu1269(有向图强连通分量)
    bzoj2159: Crash 的文明世界
  • 原文地址:https://www.cnblogs.com/pinpin/p/10239612.html
Copyright © 2011-2022 走看看