天天看點

python3 urllib 連結中有中文的解決方法解決方法

環境python3,開發平台pycharm,使用urllib時,當url中存在中文時會出現以下錯誤:

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

解決方法

單獨處理url中的中文如:

import urllib
s=‘中文’
s=urllib.parse.quote(s)
url='some english url character %s'%(s)
result=urllib.request.urlopen(url)
print(result)
           

此時傳回結果,但是依然為亂碼,需要對去結果解碼

print(result.decode('utf-8'))
           

至此,問題解決!!!

原因後續再解釋。

繼續閱讀