我需要一些关于列表编码的帮助。我是 python 的新手,抱歉。 首先,我使用的是 Python 2.7.3
我有两个列表(entidad 和 valores),我需要对它们进行编码或类似的操作。
我的代码:
import urllib
from bs4 import BeautifulSoup
import csv
sock = urllib.urlopen("http://www.fatm.com.es/Datos_Equipo.asp?Cod=01HU0010")
htmlSource = sock.read()
sock.close()
soup = BeautifulSoup(htmlSource)
form = soup.find("form", {'id': "FORM1"})
table = form.find("table")
entidad = [item.text.strip() for item in table.find_all('td')]
valores = [item.get('value') for item in form.find_all('input')]
valores.remove('Imprimir')
valores.remove('Cerrar')
header = entidad
values = valores
print values
out = open('tomate.csv', 'w')
w = csv.writer(out)
w.writerow(header)
w.writerow(values)
out.close()
日志:UnicodeEncodeError: 'ascii' codec can't encode character
有什么想法吗?提前致谢!!
请您参考如下方法:
您应该手动将数据编码为 utf-8,csv.writer 没有为您完成:
w.writerow([s.encode("utf-8") for s in header])
w.writerow([s.encode("utf-8") for s in values])
#w.writerow(header)
#w.writerow(values)
