BubblewrapBeast
BubblewrapBeast

Reputation: 1607

UnicodeEncodeError saving to file

I can't seem to get this to work no matter what decode and encode I try. I am currently getting the error: UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013'

This error does change however if I am to add decoding and encoding/

browser = webdriver.Firefox()
time.sleep(5)
browser.get("http://agentblackhat.com/")
time.sleep(5)
browser.find_element_by_xpath('//*[@id="primary-left"]/article[1]/h3/a').click()
time.sleep(5)
title = browser.find_element_by_xpath("/html/body/div/div[2]/div[1]/article/h3").text
time.sleep(3)
des = browser.find_element_by_xpath("/html/body/div/div[2]/div[1]/article/div[3]/h2[1]").text

tf = 'textfile.txt'
f2 = open(tf, 'a+')
f2.write(', '.join([str(data) for data in [title,des]]) + '\n')
f2.close()

Thanks!

Upvotes: 1

Views: 127

Answers (2)

Irshad Bhat
Irshad Bhat

Reputation: 8709

Replace:

f2.write(', '.join([str(data) for data in [title,des]]) + '\n')

with:

f2.write(', '.join([data.encode('utf-8') for data in [title,des]]) + '\n')

Upvotes: 1

wolendranh
wolendranh

Reputation: 4292

Try to use on you strings:

.encode('utf-8')

Upvotes: 0

Related Questions