TypeError:需要一个字节类型的对象,而不是'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')

To:

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)

我在Python3上也遇到了同样的问题。 我的代码正在写入io.BytesIO()。

用io.StringIO()替换解决了。


file = open('parsed_data.txt', 'w')
for link in soup.findAll('a', attrs={'href': re.compile("^http")}): print (link)
soup_link = str(link)
print (soup_link)
file.write(soup_link)
file.flush()
file.close()

在我的例子中,我使用BeautifulSoup用Python 3.x编写了一个.txt。它也有同样的问题。就像@tsduteba说的,把第一行的'wb'改成'w'。


只要把wb改成w

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

to

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

您以二进制模式打开csv文件,它应该是'w'

import csv

# open csv file in write mode with utf-8 encoding
with open('output.csv','w',encoding='utf-8',newline='')as w:
    fieldnames = ["SNo", "States", "Dist", "Population"]
    writer = csv.DictWriter(w, fieldnames=fieldnames)
    # write list of dicts
    writer.writerows(list_of_dicts) #writerow(dict) if write one row at time