簡體   English   中英

類型錯誤:需要一個類似字節的對象,而不是 python 和 CSV 中的“str”

[英]TypeError: a bytes-like object is required, not 'str' in python and CSV

類型錯誤:需要類似字節的對象,而不是“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)

在最后一行的上方。

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

改變:

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

到:

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

您將獲得一個具有以下輸出的文件:

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

在 Python 3 中 csv 以文本模式接受輸入,而在 Python 2 中以二進制模式接受輸入。

編輯添加

這是我運行的代碼:

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)

我在 Python3 上遇到了同樣的問題。 我的代碼正在寫入io.BytesIO()

替換為io.StringIO()解決了。

只需將 wb 更改為 w

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

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

您正在以二進制模式打開 csv 文件,它應該是'w'

import csv

# open csv file in write mode with utf-8 encoding
with open('output.csv','w',encoding='utf-8',newline='')as w:
    fieldnames = ["SNo", "States", "Dist", "Population"]
    writer = csv.DictWriter(w, fieldnames=fieldnames)
    # write list of dicts
    writer.writerows(list_of_dicts) #writerow(dict) if write one row at time
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”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM