gpt4 book ai didi

python - python 和 CSV 中的 TypeError : a bytes-like object is required, 不是 'str'

转载 作者:行者123 更新时间:2023-12-03 04:24:05 26 4
gpt4 key购买 nike

TypeError: a bytes-like object is required, not '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)

最佳答案

您正在使用 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)

关于python - python 和 CSV 中的 TypeError : a bytes-like object is required, 不是 'str',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34283178/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com