from urllib import requesturl = 'http://httpbin.org/post'headers = { 'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36', 'Host':'httpbin.org', 'Chinese':'李寧',}req = request.Request(url = url,headers=headers,method="POST")request.urlopen(req)
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-1: ordinal not in range(256)
from urllib.parse import unquote,urlencodevalue = urlencode({'name':'李寧'})print(value)print(unquote(value))
name=%E6%9D%8E%E5%AE%81name=李寧
import base64# 對中文進行編碼base64Value = base64.b64encode(bytes('Python從菜鳥到高手',encoding='utf-8'))print(str(base64Value,'utf-8'))# 對中文進行解碼,並按utf-8編碼格式將解碼後的結果轉換爲字符串print(str(base64.b64decode(base64Value),'utf-8'))
from urllib import requestfrom urllib.parse import unquote,urlencodeimport base64url = 'http://httpbin.org/post'headers = { 'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36', 'Host':'httpbin.org', 'Chinese1':urlencode({'name':'李寧'}), # 設置中文HTTP請求頭,用url編碼格式 # 設置中文HTTP請求頭,用base64編碼格式 'MyChinese':base64.b64encode(bytes('這是中文HTTP請求頭',encoding='utf-8')), 'who':'Python Scrapy'}dict = { 'name':'Bill', 'age':30}data = bytes(urlencode(dict),encoding='utf-8')req = request.Request(url = url,data=data,headers=headers,method="POST")# 經過add_header方法添加中文HTTP請求頭,url編碼格式req.add_header('Chinese2',urlencode({"國籍":"中國"}))response=request.urlopen(req)# 獲取服務端的響應信息value = response.read().decode('utf-8')print(value)import json# 將返回值轉換爲json對象responseObj = json.loads(value)# 解碼url編碼格式的HTTP請求頭print(unquote(responseObj['headers']['Chinese1']))# 解碼url編碼格式的HTTP請求頭print(unquote(responseObj['headers']['Chinese2']))# 解碼base64編碼格式的HTTP請求頭print(str(base64.b64decode(responseObj['headers']['Mychinese']),'utf-8'))
- EOF -javascript
臥槽,好強大的魔法,竟能讓Python支持方法重載
python
Python裝飾器(decorator)不過如此,是我想多了web
這樣合併Python字典,能夠讓程序的運行效率提升4倍json
Python代碼能夠加密嗎?Python字節碼告訴你!swift
關注「極客起源」公衆號,加星標,不錯過精彩技術乾貨
函數
本文分享自微信公衆號 - 極客起源(geekculture)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。