str socket pasar not expected convert bytes csv python-3.x beautifulsoup html-table

socket - typeerror a bytes like object is required not str csv python



TypeError: se requiere un objeto similar a bytes, no ''str'' en python y CSV (4)

TypeError: se requiere un objeto similar a bytes, no ''str''

obteniendo el error anterior mientras se ejecuta el código python debajo para guardar los datos de la tabla HTML en el archivo Csv. no sé cómo obtener rideup.pls ayúdame.

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)

encima de la última línea.


Está utilizando la metodología Python 2 en lugar de Python 3.

Cambio:

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

A:

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

y obtendrá un archivo con el siguiente resultado:

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 .....

En Python 3, csv toma la entrada en modo texto, mientras que en Python 2 la toma en modo binario.

Editado para agregar

Aquí está el código que ejecuté:

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)


Tuve el mismo problema con Python3. Mi código estaba escribiendo en io.BytesIO() .

Reemplazando con io.StringIO() resuelto.


solo cambia wb a w

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

a

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


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()

En mi caso, utilicé BeautifulSoup para escribir un archivo .txt con Python 3.x. Tuvo el mismo problema. Tal como dijo @tsduteba, cambie el ''wb'' en la primera línea a ''w''.