【问题标题】:UnicodeEncodeError: 'charmap' codec can't encode character '\x97' in position 206: character maps to <undefined>UnicodeEncodeError:“charmap”编解码器无法在位置 206 编码字符“\x97”:字符映射到 <undefined>
【发布时间】:2018-12-10 17:57:51
【问题描述】:

Windows 7 版本 Python36-32 代码用途:网站解析

您能否建议错误的可能原因是什么? 我在开头包含编码 utf-8,在函数“open”中包含 (encoding = 'windows_1252', errors = 'replace') 它在其他网站的其他类似解析器中帮助了我,但对于这个不起作用

**一段代码:

# cycle through pages
     for i in range (count):
         s = str (i + 1)
         print (s, end = '')
         # make url
         url = url1 + s + url2 + str (status) + url3
         # get html file from server by url
         r = requests.get (url)
         # open file to save with full path to file name
         name = path + 'upload' + s + '.html'
         f = open (name, 'w', encoding = 'windows_1252', errors = 'replace')
         # save url data to file
         f.write (r.text)
         # close file
         f.close ()
         # download files through the list
         parseList (name, s + '.html')

     print ()
     return

错误文字:

Traceback (most recent call last):
  File "C:\Users\u6030283\Desktop\FINAM\finam_parser_new.py", line 478, in <module>
    parse('list', 'html', 'XS1272198265')
  File "C:\Users\u6030283\Desktop\FINAM\finam_parser_new.py", line 262, in parse
    f.write(r.text)
  File "C:\Users\u6030283\AppData\Local\Programs\Python\Python36-32\lib\encodings\cp1251.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\x97' in position 206: character maps to <undefined>

【问题讨论】:

    标签: python


    【解决方案1】:

    更新:

    问题不是来自上面的代码(写入文件),而是来自parse()parseList() 方法或来自读取文件。

    替换以下内容

    # in parseList(...)
    text = open(url, 'r')
    
    # and in parse(..)
    text = open(path + file, 'r') 
    

    # in parseList(...)
    text = open(url, 'r', encoding='windows_1252')
    
    # and in parse(..)
    text = open(path + file, 'r', encoding='windows_1252') 
    

    并且不要忘记将上述问题中的代码恢复到原始状态。

    【讨论】:

    • Traceback(最近一次调用最后一次):文件“C:\Users\u6030283\Desktop\FINAM\finam_parser_new.py”,第 475 行,在 upload(5,'upload', 4 ) 文件“C:\Users\u6030283\Desktop\FINAM\finam_parser_new.py”,第 163 行,上传 f.write(r.text.encode('utf-8')) TypeError: write() argument must be str ,而不是字节
    • 出现其他错误
    • 尝试删除encoding = 'windows_1252', errors = 'replace'
    • 同样的错误 :(
    • UnicodeEncodeError: 'charmap' codec can't encode character '\x97' in position 206: character maps to
    猜你喜欢
    • 1970-01-01
    • 2018-07-30
    • 2021-01-27
    • 2014-01-06
    • 1970-01-01
    • 2022-06-11
    • 2013-02-17
    • 1970-01-01
    • 2015-11-29
    相关资源
    最近更新 更多