2017-09-25 96 views
1

我有這樣的代碼:UnicodeEncodeError: 'ASCII' 編解碼器在90-96位置無法編碼的字符:順序不在範圍內(128)

url= 'https://yandex.ru/search/xml?user=uid-2h3232xfhboy&key=03.292922330523:6b4c80ghghghhghgdsfdsfds4c4b4a7872fb7d2bb04bfdgbb02b76c3d&query=' 
key = "абс" 
url = url + key 
     print(url) 
     xml = urllib.request.urlopen(url).read() 

但我得到一個錯誤:

UnicodeEncodeError: 'ascii' codec can't encode characters in position 90-96: ordinal not in range(128) 

我該怎麼辦?

我試過url= url.encode("utf-8") 但沒有幫助。得到這個錯誤:

AttributeError: 'bytes' object has no attribute 'timeout'

我試着這樣做: url = u''.join((self.ya_url, key)).encode('utf-8') 由於這裏建議:UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)

,但得到了同樣的錯誤

AttributeError: 'bytes' object has no attribute 'timeout'

我該怎麼辦?

+0

您是否已經通過了與此非常相似的其他問答? (請參閱「相關」側邊欄。) – glibdud

+0

@glibdud是的,我已經通過一些與此非常相似的問答(請參閱最後3段問題) – user2950593

+0

請參閱[此問題](https://stackoverflow.com/questions/24049151/attributeerror-bytes-object-has-no-attribute-timeout)來解釋AttributeError。 – glibdud

回答

2

您不能在URL中使用非ASCII字符。您需要適當地引用您的key值:

import urllib.parse 

url= 'https://yandex.ru/search/xml?user=uid-2h3232xfhboy&key=03.292922330523:6b4c80ghghghhghgdsfdsfds4c4b4a7872fb7d2bb04bfdgbb02b76c3d&query=' 
key = "абс" 
quoted = urllib.parse.quote(key) 
url = url + quoted 
相關問題