2017-06-17 147 views
0

所以我有這段代碼片斷,每當我嘗試執行它時都會返回一個錯誤。python error「quote_from_bytes()expected bytes」

下面是代碼,它應該基於靈活的字符串參數量來進行谷歌圖像搜索。

@bot.command() 
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('http://ajax.googleapis.com/ajax/services/search/images?q=' + q + '&v=1.0&rsz=large&start=1') 
    data = json.load(f) 
    f.close() 

我得到這個錯誤,當我嘗試但是執行它:

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

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

任何幫助,將不勝感激

回答

0

args字符串列表?如果是這樣,你應該將它們轉換爲urllib.parse.quote的字節以正常工作。

變化q += urllib.parse.quote(arg) + '+'q += urllib.parse.quote(arg.encode('utf-8')) + '+'q += urllib.parse.quote(bytes(arg)) + '+'

+0

這樣做之後,我得到一個新的錯誤,AttributeError的:「元組」對象有沒有屬性「編碼」 –

+0

這裏只是注意到了另一個問題。 '枚舉中的arg(args):'應該是'args'中的arg'。或者如果你需要使用枚舉(爲了調試或其他原因),它應該是'for _,arg in enumerate(args)' –

相關問題