2

I need some help with the encoding of a list. I'm new in python, sorry. First, I'm using Python 2.7.3

I have two lists (entidad & valores), and I need to get them encoded or something of that.

My code:

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

the log: UnicodeEncodeError: 'ascii' codec can't encode character

any ideas? Thanks in advance!!

2
  • 1
    Did you google your error message? Here's the top result: stackoverflow.com/questions/9942594/… Commented Feb 28, 2014 at 16:04
  • I always google this simple things, but I couldn't understand well, sorry. Commented Feb 28, 2014 at 16:13

2 Answers 2

2

You should encode your data to utf-8 manually, csv.writer didnt do it for you:

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)
Sign up to request clarification or add additional context in comments.

Comments

0

This appears to be the same type of problem as had been found here UnicodeEncodeError in csv writer in Python

UnicodeEncodeError in csv writer in Python
Today I was writing a program that generates a csv file after some processing. But I got the following error while trying on some test data:

writer.writerow(csv_li) UnicodeEncodeError: 'ascii' codec can't encode character u'\xbf' in position 5: ordinal not in range(128)

I looked into the documentation of csv module in Python and found a class named UnicodeWriter. So I changed my code to

writer = UnicodeWriter(open("filename.csv", "wb"))

Then I tried to run it again. It got rid of the previous UnicodeEncodeError but got into another error.

self.writer.writerow([s.encode("utf-8") for s in row]) AttributeError: 'int' object has no attribute 'encode'

So, before writing the list, I had to change every value to string.

row = [str(item) for item in row]

I think this line can be added in the writerow function of UnicodeWriter class.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.