urllib.requet

請(qǐng)求與響應(yīng) .urlopen()

urllib.request.Request() 類(lèi)型實(shí)例

import urllib.request #申請(qǐng)一個(gè)請(qǐng)求
import utllib.parse #格式化字符串
url = 'http://httpbin.org/get'
req = urllib.request.Request(url)
rsp = urllib.request.urlopen(req)
rsp.status #請(qǐng)求狀態(tài)

.add_header(key,value) 添加頭部信息

import urllib.error
import urllib.request
import urllib.parse
url = 'http://httpbin.org/get'
req = urllib.request.Request(url, method='GET')
req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36')
rsq = urllib.request.urlopen(req)
b = rsq.read()
from pprint import pprint
pprint(b.decode())



('{\n'
 '  "args": {}, \n'
 '  "headers": {\n'
 '    "Accept-Encoding": "identity", \n'
 '    "Connection": "close", \n'
 '    "Host": "httpbin.org", \n'
 '    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
 'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36"\n'
 '  }, \n'
 '  "origin": "175.167.138.151", \n'
 '  "url": "http://httpbin.org/get"\n'
 '}\n')

.Request(url,data='數(shù)據(jù)') 構(gòu)造POST訪問(wèn)

import urllib.request
import urllib.parse
url = 'http://httpbin.org/post'
form = {'name':'Jin', 'age':20}
data = urllib.parse.urlencode(form)
data = data.encode()
req = urllib.request.Request(url, data=data)
rsq = urllib.request.urlopen(req)
b = rsq.read()
b = b.decode()
from pprint import pprint
pprint(b)



('{\n'
 '  "args": {}, \n'
 '  "data": "", \n'
 '  "files": {}, \n'
 '  "form": {\n'
 '    "age": "20", \n'
 '    "name": "Jin"\n'
 '  }, \n'
 '  "headers": {\n'
 '    "Accept-Encoding": "identity", \n'
 '    "Connection": "close", \n'
 '    "Content-Length": "15", \n'
 '    "Content-Type": "application/x-www-form-urlencoded", \n'
 '    "Host": "httpbin.org", \n'
 '    "User-Agent": "Python-urllib/3.6"\n'
 '  }, \n'
 '  "json": null, \n'
 '  "origin": "175.167.138.151", \n'
 '  "url": "http://httpbin.org/post"\n'
 '}\n')


結(jié)果 http.client.HTTPResponse

  • .status 狀態(tài)碼
  • .getcode() 獲取狀態(tài)碼
  • .reason 狀態(tài)文本
  • .geturl() 獲取URL
  • .info() 獲取元信息
  • .read() 讀取正文到字節(jié)

傳參

data = {'name':'xxx', 'age':'xx'}
params = urllib.parse.urlencode(data)
rsp = urllib.request.urlopen(f'{url}?{params}')
b = rsp.read()
s = b.decode()
from pprint import pprint
pprint(s)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容