TypeError: un object de type octet est requirejs, pas «str» dans python et CSV

TypeError: un object de type octet est requirejs, pas «str»

obtenir au-dessus de l’erreur lors de l’exécution en dessous du code python pour enregistrer les données du tableau HTML dans un fichier CSV. Je ne sais pas comment obtenir rideup.pls aidez-moi.

import csv import requests from bs4 import BeautifulSoup url='http://www.mapsofindia.com/dissortingcts-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) 

au-dessus de la dernière ligne.

Vous utilisez la méthodologie Python 2 au lieu de Python 3.

Changement:

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

À:

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

et vous obtiendrez un fichier avec la sortie suivante:

 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 prend l’entrée en mode texte, alors qu’en Python 2, elle le prend en mode binary.

Edité pour append

Voici le code que j’ai couru:

 url='http://www.mapsofindia.com/dissortingcts-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) 

J’ai eu le même problème avec Python3. Mon code écrivait dans io.BytesIO() .

Remplacement par io.SsortingngIO() résolu.

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

Dans mon cas, j’ai utilisé BeautifulSoup pour écrire un fichier .txt avec Python 3.x. Il y avait le même problème. Juste comme @tsduteba a dit, changez le “wb” dans la première ligne à “w”.