【问题标题】:Writing to a file but getting ASCII encoding error写入文件但出现 ASCII 编码错误
【发布时间】:2018-06-13 06:40:09
【问题描述】:

我正在尝试从网站上的表格中抓取数据。

page_soup = soup(html, 'html.parser')
stat_table = page_soup.find_all('table')
stat_table = stat_table[0]

with open ('stats.txt','w') as q:
for row in stat_table.find_all('tr'):
    for cell in row.find_all('td'):
        q.write(cell.text)

但是,当我尝试写入文件时,我收到以下错误消息:'ascii' codec can't encode character '\xa0' in position 19: ordinal not in range(128)。

我知道应该用.encode('utf-8')编码,但是

cell.text.encode('utf-8')

不起作用。

任何帮助将不胜感激。使用 Python 3.6

【问题讨论】:

    标签: python encoding ascii file-writing


    【解决方案1】:

    文件编码由当前环境确定,在本例中假设为 ascii。可以直接使用指定文件编码:

    with open ('stats.txt', 'w', encoding='utf8') as q:
        pass
    

    【讨论】:

      猜你喜欢
      • 2016-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-20
      • 1970-01-01
      • 2016-04-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多