4

I'm trying to print out the following request in Python (using the requests module):

r = requests.get("http://www.youtube.com", 
                params={
                    "search_query": "test"
                }).text 

However, when printing, I get the following error:

UnicodeEncodeError: 'charmap' codec can't encode characters in position 32891-32894: character maps to <undefined>

I'm sure it's not the module itself, as there seem to be no other occurrences of this based on some googling, and the fact that it's working with other requests I try. It seems to be only this request that cannot be printed.

Would anyone know how to print it?

Edit: Now I'm really confused: this program worked once for me, and has not worked once since that one occurence.

Cisplatin
  • 2,860
  • 3
  • 36
  • 56
  • possible duplicate of [Help me understand why Unicode only works sometimes with Python](http://stackoverflow.com/questions/5695421/help-me-understand-why-unicode-only-works-sometimes-with-python) – Sean Redmond Jul 07 '13 at 19:29
  • That question asks about outputting non-standard characters, whereas this one asks about outputting requests. – Cisplatin Jul 07 '13 at 19:32
  • I was going to recommend some kind of ignore flag - like endcode('ascii','ignore") for example (if that works for you), but while checking for it, I can't reproduce the issue. Your code works for me as is. – bsoist Jul 07 '13 at 19:38
  • How are you printing? Just print r? – Cisplatin Jul 07 '13 at 19:51
  • The problem is just that when you print the request, the console can't handle Unicode characters. It doesn't have anything to do with the request except that the request is in Unicode: – Sean Redmond Jul 07 '13 at 20:17

1 Answers1

6

In case of python 2.x, you need to encode the string before you can print it.

Try:

print r.encode('utf-8')
shantanoo
  • 3,617
  • 1
  • 24
  • 37