为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕村225694 2019-10-29 11:10:34
TypeError:需要一个类似字节的对象,而不是'str'在执行以下python代码以将HTML表格数据保存到Csv文件时遇到上述错误。不知道如何获得rideup.pls帮助我。import csvimport requestsfrom bs4 import BeautifulSoupurl='http://www.mapsofindia.com/districts-india/'response=requests.get(url)html=response.contentsoup=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)在最后一行上方。
查看完整描述

3 回答

?
守着星空守着你

TA贡献1799条经验 获得超8个赞

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'。


查看完整回答
反对 回复 2019-10-29
?
料青山看我应如是

TA贡献1772条经验 获得超8个赞

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

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


查看完整回答
反对 回复 2019-10-29
  • 3 回答
  • 0 关注
  • 424 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信