1. 程式人生 > >python實現http get請求

python實現http get請求

value lis lib 編碼 The 打開 中文編碼 ror 記錄

  • 接口請求方式為get請求,如下圖抓包查看

技術分享圖片

  • Python實現腳本請求接口並以中文打印接口返回的數據
 1 import urllib.parse
 2 import urllib.request
 3 
 4 url = "https://..../manage/region/list"
 5 
 6 # 定義請求數據,並且對數據進行賦值
 7 values={}
 8 values[status]= hq
 9 values[token]= C6AD7DAA24BAA29AE14465DDC0E48ED9
10 
11 # 對請求數據進行編碼
12 data = urllib.parse.urlencode(values).encode(
utf-8) 13 print(type(data)) # 打印<class bytes> 14 print(data) # 打印bstatus=hq&token=C6AD7DAA24BAA29AE14465DDC0E48ED9 15 16 # 若為post請求以下方式會報錯TypeError: POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str. 17 # Post的數據必須是bytes或者iterable of bytes,不能是str,如果是str需要進行encode()編碼
18 data = urllib.parse.urlencode(values) 19 print(type(data)) # 打印<class str> 20 print(data) # 打印status=hq&token=C6AD7DAA24BAA29AE14465DDC0E48ED9 21 22 # 將數據與url進行拼接 23 req = url + ? + data 24 # 打開請求,獲取對象 25 response = urllib.request.urlopen(req) 26 print(type(response)) # 打印<class
http.client.HTTPResponse> 27 # 打印Http狀態碼 28 print(response.status) # 打印200 29 # 讀取服務器返回的數據,對HTTPResponse類型數據進行讀取操作 30 the_page = response.read() 31 # 中文編碼格式打印數據 32 print(the_page.decode("unicode_escape"))

  • 執行腳本,接口返回數據

技術分享圖片

  • 使用到的函數

urllib.parse.urlencode() 把key-value這樣的鍵值對轉換成a=1&b=2這樣的字符串

urllib.request.urlopen() 打開指定的url,就是進行get請求

response.read() 讀取HTTPResponse類型數據

  • 腳本執行過程報錯記錄,requests爬蟲時開啟代理會報以下錯誤

requests.exceptions.SSLError: HTTPSConnectionPool(host=‘api.****.cn‘, port=443):Max retries exceeded with url: //manage/region/list (Caused by SSLError(SSLError("bad handshake: Error([(‘SSL routines‘, ‘tls_process_server_certificate‘, ‘certificate verify failed‘)])")))

python實現http get請求