运行python脚本时出现Unicode错误

运行python脚本时出现Unicode错误,python,python-3.x,beautifulsoup,python-unicode,Python,Python 3.x,Beautifulsoup,Python Unicode,我编写了以下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://fin

我编写了以下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\u of_companys.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>
回溯(最近一次呼叫最后一次):
文件“C:\Users\Darshil Babel\Desktop\NewsContent\s.py”,第12行,在
f1.书写(soup.prettify())
文件“C:\Python34\lib\encodings\cp1252.py”,第19行,在encode中
返回codecs.charmap\u encode(输入、自身错误、编码表)[0]
UnicodeEncodeError:“charmap”编解码器无法对1556位置的字符“\u03cb”进行编码:字符映射到
为此,我正在使用urllibBeautifulSoup模块。
有人能帮我一下吗?

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

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