1. 程式人生 > >python中文編碼問題解決UnicodeEncodeError: 'ascii' codec can't encode characters in position 10-14: ordinal n

python中文編碼問題解決UnicodeEncodeError: 'ascii' codec can't encode characters in position 10-14: ordinal n

編碼報錯:

https://www.baidu.com/s?wd=渴望飛的魚 UnicodeEncodeError: 'ascii' codec can't encode characters in position 10-14: ordinal not in range(128)

原因:

由於編碼問題造成的,解決方法如下:

key=urllib.request.quote(keyworld)轉換一下。
#http協議請求,客戶端與服務端進行訊息傳遞
#get請求
"""
在瀏覽器輸入關鍵字,回車,url變化。
https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=0&rsv_idx=1&tn=baidu
&wd=hello&rsv_pq=f218eac10000df63&rsv_t=3615gHwrY%2FUiWRMS%2Fh3pT5KyEK755vjJ%2F2wKMOK%2BPwDS6uh0nWg%2BI32RUpU
&rqlang=cn&rsv_enter=1&rsv_sug3=7&rsv_sug1=8&rsv_sug7=101
得出,wd=hello,關鍵詞是wd
可以簡化為:https://www.baidu.com/s?wd=hello
"""
import urllib.request
keyworld="渴望飛的魚"
key=urllib.request.quote(keyworld)
url="https://www.baidu.com/s?wd="+key
print(url)
req=urllib.request.Request(url)
data=urllib.request.urlopen(req).read()
fhandle=open('D:/爬蟲/抓取檔案/2018110205.html','wb')
fhandle.write(data)
fhandle.close()

執行結果:

D:\工具\pythonTools\CatchTest1101\venv\Scripts\python.exe D:/工具/pythonTools/CatchTest1101/venv/test/test110207.py
https://www.baidu.com/s?wd=%E6%B8%B4%E6%9C%9B%E9%A3%9E%E7%9A%84%E9%B1%BC

Process finished with exit code 0

同時生成成功