【问题标题】:UnicodeEncode Error while running a python script运行 python 脚本时出现 UnicodeEncode 错误
【发布时间】:2014-10-16 06:09:15
【问题描述】:

我编写了以下 python 脚本,用于从 Yahoo Finance 网站检索信息并将其存储在文件中。以下是脚本:

import urllib.request
from bs4 import BeautifulSoup
in_data = open('list_of_companies.txt','r',encoding='utf-8', errors='ignore')
for line in in_data:
    page = urllib.request.urlopen('http://finance.yahoo.com/rss/headline?s='+line.strip())
    page = page.read()
    page = page.decode('utf-8','ignore')
    soup = BeautifulSoup(page)
    ans = line[0:len(line.strip())]
    ans += '.txt'
    f1 = open(ans,'w')
    f1.write(soup.prettify())
    f1.close()

它将从list_of_companies.txt 获取输入符号并将其存储在具有该名称的文件中。但是,当我运行这个脚本时,这给了我以下错误:

Traceback (most recent call last):
  File "C:\Users\Darshil Babel\Desktop\NewsContent\s.py", line 12, in <module>
    f1.write(soup.prettify())
  File "C:\Python34\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u03cb' in position 1556: character maps to <undefined>

我为此目的使用 urllibBeautifulSoup 模块。 有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: python python-3.x beautifulsoup python-unicode


    【解决方案1】:

    您打开输出文件时未指定与 Unicode 兼容的编码。试试

    f1 = open(ans,'w', encoding='utf-8')
    

    【讨论】:

      猜你喜欢
      • 2019-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-17
      • 2020-08-02
      • 2022-01-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多