Request庫基本使用

2022-01-12 05:54:24 字數 3439 閱讀 9507

基本例項

import

requests

url= '

'response =requests.get(url)

print

(type(response))

print(response.status_code)#

狀態碼print

(type(response.text))

print(response.text)#

開啟網頁源**

print(response.cookies)#

獲取cookies

各種請求方式

import

requests

url= '

'requests.get(url)

requests.put(url)

requests.delete(url)

requests.head(url)

requests.options(url)

帶引數的get請求

import

requests

data=

reponse = requests.get(url,params=data)

解析json

import

requests

import

json

reponse =requests.get(url)

print

(requests.json())

print(json.loads(reponse.text))

獲取二進位制資料和儲存

import

requests

import

json

reponse =requests.get(url)

print

(reponse.text)

print(reponse.content)

import

requests

import

json

reponse =requests.get(url)

with open(

'','

') as f:

f.write(reponse.content)

f.close()

新增headers

import

requests

import

json

headers =

response = requests.get(url,headers=headers)

基本post請求

mport requests

import

json

data =

headers=

response = requests.post(url,data=data,headers=headers)

reponse屬性

import

requests

url= '

'response =requests.get(url)

print

(type(response))

print(response.status_code)#

狀態碼print

(type(response.text))

print(response.text)#

開啟網頁源**

print(response.cookies)#

獲取cookies

print

(response.history)

print(response.url)

檔案上傳

import

requests

files =

reponse = requests.post(url,files=files)

維持會話

import

requests

s =requests.session()

s.get(url_1)

response = s.get(url_2)

證書認證

import

requests

from requests.packages import

urllib3

urllib3.disable_warnings()

#消除警告

pip3 install 'requests[socks]' 使用socks**

import

requests

from requests.exceptions import

readtimeout

try:

response = requests.get(url,timeout=)

except

readtimeout:

print("

time out

")

認證設定

異常處理

request庫的基本用法

request urllib 獲取url 獲取狀態碼 request.states code response.getcode 返回html request.text response.read 獲得頭部資訊 request.headers response.info 返回請求的url reques...

請求庫 request使用

coding utf 8 import requests from urllib.parse import urlencode keyword input strip res urlencode encoding utf 8 url res print url response requests.g...

Request庫的使用

request庫 封裝了自動爬取html頁面,自動網路請求提交的方法的庫 request庫的7個主要方法 requests.request 構造乙個請求,是一下個方法的基礎 requests.get 獲取html網頁的主要方法,對應於http的get requests.head 獲取html網頁頭部...