python requests的簡(jiǎn)單應(yīng)用

requests

引入

import requests

簡(jiǎn)單請(qǐng)求

r = requests.get("http://httpbin.org/get")
r = requests.post("http://httpbin.org/post")
r = requests.put("http://httpbin.org/put")
r = requests.delete("http://httpbin.org/delete")
r = requests.head("http://httpbin.org/get")
r = requests.options("http://httpbin.org/get")

帶參請(qǐng)求

params = {"query" : "東方樹葉"}
r = requests.get("https://www.sogou.com/web", params=params)
print(r.text)

text和content的區(qū)別

  • r.text 返回的是unicode的數(shù)據(jù)
  • r.content 返回的是二進(jìn)制數(shù)據(jù)(用于圖片、文件)
r = requests.get("https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png")

with open('1.jpg', 'wb') as f:
    f.write(r.content)

內(nèi)置json函數(shù)

r = requests.get("http://httpbin.org/ip")
print(r.json()["origin"])
// 103.30.48.250

網(wǎng)頁(yè)狀態(tài)嗎

// allow_redirects = False 禁止跳轉(zhuǎn)

r = requests.get("http://httpbin.org/redirect-to?url=http://www.baidu.com", allow_redirects = False)
print(r.status_code)
// 302

響應(yīng)頭

r = requests.get("http://httpbin.org/get")
print(r.headers)
print(r.headers["Content-Type"])

超時(shí)設(shè)置

try:
    r = requests.get("http://github.com", timeout = 0.01)
    print(r)
except:
    print("超時(shí)")

代理訪問(wèn)

proxies = {
    "http" : "http://91.121.162.173:80",
    "https" : "https://60.168.246.71:808"
}

r = requests.get("http://httpbin.org/get", proxies = proxies)

請(qǐng)求頭內(nèi)容

r = requests.get("http://httpbin.org/get")
print(r.request.headers)

自定義請(qǐng)求頭

headers = {
    "User-Agent" : "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36"
}
r = requests.get("http://httpbin.org/get", headers = headers)
print(r.request.headers)

擴(kuò)展

官方中文文檔:http://docs.python-requests.org/zh_CN/latest/index.html
http很不錯(cuò)的測(cè)試工具:http://httpbin.org/

最后編輯于
?著作權(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)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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