猿问

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

TypeError:需要一个类似字节的对象,而不是'str'


在执行以下python代码以将HTML表格数据保存到Csv文件时遇到上述错误。不知道如何获得rideup.pls帮助我。


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)

在最后一行上方。


慕村225694
浏览 425回答 3
3回答

守着星空守着你

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

料青山看我应如是

我在Python3中遇到了同样的问题。我的代码正在写入io.BytesIO()。替换为已io.StringIO()解决。
随时随地看视频慕课网APP

相关分类

Python
我要回答