我在Python2.7中运行了一个非常简单的BeautifulSoup,我需要在Python3中运行它。输出是一个csv文件。在Python2中,我可以将其直接导入Excel,但在Python3中,字段会出现在b' text'并以该形式加载到单元格中。我从未接触过Python3,所以会很感激一些指导。
相关代码是:
for d in data:
row = []
name = d.find('a')
addr = d.find('span', attrs = {'class' : 'center_address'})
city = d.find('span', attrs = {'class' : 'center_city'})
state = d.find('span', attrs = {'class' : 'center_state_abbr'})
zip = d.find('span', attrs = {'class' : 'center_zip'})
row.append(str(name.text))
row.append(addr.text)
row.append(city.text)
row.append(state.text)
row.append(zip.text)
list_of_rows.append(row)
with open("./output.csv", "w") as outfile:
writer = csv.writer(outfile)
writer.writerow(["Name","Address", "City","State","Zip"])
writer.writerows([s.strip().encode("utf-8") for s in row ]for row in list_of_rows)
outfile.close()
答案 0 :(得分:1)
您已在文本模式下打开输出文件,这意味着您应该向其发送Unicode文本字符串,但您不是 - 您正在使用Unicode字符串并将它们转换为编码字节数据。
删除编码步骤,使代码读取
with open("./output.csv", "w") as outfile:
writer = csv.writer(outfile)
writer.writerow(["Name","Address", "City","State","Zip"])
writer.writerows(([s.strip() for s in row ]
for row in list_of_rows))
将在Python 3下运行。