简体   繁体   English

试图在Python中将变量写入文件,但出现UnicodeEncodeError

[英]Trying to write a variable to a file in Python, and I get UnicodeEncodeError

I am working on making my CS:GO Match Simulator automatically grab statistics about teams and players. 我正在努力使CS:GO比赛模拟器自动获取有关球队和球员的统计信息。 To do that, I need the "text" variable written to a text file. 为此,我需要将“ text”变量写入文本文件。 If someone can help me with this, that would be great. 如果有人可以帮助我,那就太好了。 Thanks in advance! 提前致谢!

UnicodeEncodeError: 'ascii' codec can't encode character u'\\xf6' in position 58743: ordinal not in range(128) UnicodeEncodeError:'ascii'编解码器无法在位置58743上编码字符u'\\ xf6':序数不在范围内(128)

def find_source(pages):
global page
page = 1
fw = open('source_code'+str(page)+'.txt', 'w')
while page <= pages:
    url = "http://www.hltv.org/?pageid=173&playerid="+str(page)+"&eventid=0&gameid=2"
    sc = requests.get(url)
    global text
    text = sc.text
    soup = BeautifulSoup(text)
    #print (text)
    text.encode('ascii', 'ignore')
    for link in soup.findAll('a', {'class': 'tab_selected'}):
        href = "http://www.hltv.org" + link.get('href')
        title = link.string
        #fw.write(title + '\n')
        #fw.write(text)
        #fw.write(href + '\n\n')
    page += 1
fw.close()

find_source(1)

这解决了。

text = text.encode('utf-8', 'ignore')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM