TypeError:需要一个类似字节的对象,而不是 python 和 CSV 中的“str”

新手上路,请多包涵

类型错误:需要一个类似字节的对象,而不是“str”

在执行以下 python 代码以将 HTML 表格数据保存在 CSV 文件中时出现上述错误。不知道怎么上车。请帮助我。

 import csv
import requests
from bs4 import BeautifulSoup

url='http://www.mapsofindia.com/districts-india/'
response=requests.get(url)
html=response.content

soup=BeautifulSoup(html,'html.parser')
table=soup.find('table', attrs={'class':'tableizer-table'})
list_of_rows=[]
for row in table.findAll('tr')[1:]:
    list_of_cells=[]
    for cell in row.findAll('td'):
        list_of_cells.append(cell.text)
    list_of_rows.append(list_of_cells)
outfile=open('./immates.csv','wb')
writer=csv.writer(outfile)
writer.writerow(["SNo", "States", "Dist", "Population"])
writer.writerows(list_of_rows)

在最后一行之上。

原文由 ShivaGuntuku 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 498
2 个回答

您正在使用 Python 2 方法而不是 Python 3。

改变:

 outfile=open('./immates.csv','wb')

到:

 outfile=open('./immates.csv','w')

您将获得一个包含以下输出的文件:

 SNo,States,Dist,Population
1,Andhra Pradesh,13,49378776
2,Arunachal Pradesh,16,1382611
3,Assam,27,31169272
4,Bihar,38,103804637
5,Chhattisgarh,19,25540196
6,Goa,2,1457723
7,Gujarat,26,60383628
.....

在 Python 3 中,csv 以文本模式接受输入,而在 Python 2 中,它以二进制模式接受输入。

编辑添加

这是我运行的代码:

 url='http://www.mapsofindia.com/districts-india/'
html = urllib.request.urlopen(url).read()
soup = BeautifulSoup(html)
table=soup.find('table', attrs={'class':'tableizer-table'})
list_of_rows=[]
for row in table.findAll('tr')[1:]:
    list_of_cells=[]
    for cell in row.findAll('td'):
        list_of_cells.append(cell.text)
    list_of_rows.append(list_of_cells)
outfile = open('./immates.csv','w')
writer=csv.writer(outfile)
writer.writerow(['SNo', 'States', 'Dist', 'Population'])
writer.writerows(list_of_rows)

原文由 dstudeba 发布,翻译遵循 CC BY-SA 3.0 许可协议

我对 Python3 也有同样的问题。我的代码写入 io.BytesIO()

替换为 io.StringIO() 解决。

原文由 vinyll 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题