首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >TypeError:需要类似字节的对象,而不是python和CSV中的“str”

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

Stack Overflow用户
提问于 2015-12-15 15:20:35
回答 5查看 233.3K关注 0票数 207

TypeError:需要类似字节的对象,而不是“str”

执行以下python代码以将HTML表数据保存在Csv文件中时出现上述错误。不知道怎么让rideup.pls帮我。

代码语言:javascript
复制
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)

在最后一行的上方。

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2015-12-15 16:12:09

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

更改:

代码语言:javascript
复制
outfile=open('./immates.csv','wb')

至:

代码语言:javascript
复制
outfile=open('./immates.csv','w')

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

代码语言:javascript
复制
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
.....

在Python3中,csv以文本模式接受输入,而在Python2中,它以二进制模式接受输入。

编辑以添加

下面是我运行的代码:

代码语言:javascript
复制
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)
票数 406
EN

Stack Overflow用户

发布于 2016-12-23 05:20:56

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

替换为io.StringIO()已解决。

票数 31
EN

Stack Overflow用户

发布于 2019-09-18 14:02:37

只需将wb更改为w

代码语言:javascript
复制
outfile=open('./immates.csv','wb')

代码语言:javascript
复制
outfile=open('./immates.csv','w')
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34283178

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档