python error "quote_from_bytes() expected bytes"

So I have this code snippet that returns an error whenever I try to execute it.

Below is the code, it's supposed to make a google image search based on flexible amount of string arguments.

async def randomimage(*args):
    """Displays a random image of said thing"""
    q = ''

    for arg in enumerate(args):
      q += urllib.parse.quote(arg) + '+'

    f = urllib2.urlopen('' + q + '&v=1.0&rsz=large&start=1')
    data = json.load(f)

I get this error when I try to execute it however:

Traceback (most recent call last):  
File "Python36\lib\site-packages\discord\ext\commands\", line 50, in wrapped
    ret = yield from coro(*args, **kwargs)

File "", line 39, in randomimage
    q += urllib.parse.quote(arg) + '+'
  File "", line 775, in quote
    return quote_from_bytes(string, safe)
  File "", line 800, in quote_from_bytes
    raise TypeError("quote_from_bytes() expected bytes")
TypeError: quote_from_bytes() expected bytes

Any help would be appreciated

1 answer

  • answered 2017-06-17 18:02 Rishabh Srivastava

    Is args a list of strings? If so, you should convert them to bytes for urllib.parse.quote to work properly.

    Change q += urllib.parse.quote(arg) + '+' to q += urllib.parse.quote(arg.encode('utf-8')) + '+' or q += urllib.parse.quote(bytes(arg)) + '+'