1. 程式人生 > >python傳送網路請求

python傳送網路請求

1、使用urllib模組

  • get請求: res = urlopen(url)
from urllib.request import urlopen
url = 'http://www.nnzhp.cn'
print(urlopen(url))#返回http.client.HTTPResponse object at 0x00000235BA25A160
print(urlopen(url).read().decode())#返回get到的頁面的原始碼
# decode是將base型別轉為encoding 指定的編碼格式解碼字串,不指定則轉為預設編碼,如utf-8
  • post請求
from urllib.request import urlopen
from urllib.parse import urlencode

url='http://127.0.0.1:8999/api/login'
data = {'username':'testuser1','passwd':'111111'}
s = urlencode(data)
res = urlopen(url,s.encode()) #post請求
print(res.read().decode())

#最後print返回資料未請求返回資料
{
    "code": 2,
    "msg": "使用者不存在
" }

注意:帶引數的時候是一個post請求,若http://127.0.0.1:8999/api/login介面的方法限定了methods為get,則會報錯urllib.error.HTTPError: HTTP Error 405: METHOD NOT ALLOWED

  • res.read().decode()  #read()返回的值是base型別,需要通過decode轉成utf-8等;如果返回型別是json,不能使用json()方法將其轉成字典

2、使用requests模組

  • 先安裝requests模組:pip install requests
  • 然後匯入該模組 import requests
  • import requests後執行指令碼檔案,報錯如下openssl相關的資訊,則重新安裝pyOpenSSL即可。
    1 AttributeError: cffi library '_openssl' has no function, constant or global variable named 'Cryptography_HAS_NETBSD_D1_METH'
  • get請求res = requests.get(url,data=data,cookies=cookie,headers=header,verify=False,files=file)  
    • data可傳可不傳,data是字典格式。
    • 如果url是https的話,加上verify=False。如果url是http的話,可不加。
import requests

url='http://127.0.0.1:8999/api/login'
data = {'username':'testuser1','passwd':'111111'}
r = requests.get(url,params=data) #發get請求
print(r)#返回<Response [200]>
print(r.json())#將返回的json串轉為字典
print(r.text)#返回get到的頁面的返回資料

輸出結果:

<Response [200]>
{'code': 2, 'msg': '使用者不存在'}
{
    "code": 2,
    "msg": "使用者不存在"
}
  • post請求
    • res = requests.post(url,data=data,cookies=cookie,headers=header,verify=False,files=file)  
      • data是字典格式
    • res = requests.post(url,json=data,cookies=cookie,headers=header,verify=False,files=file) 
      • data是json格式
    • Cookie、header裡面只能放String 型別的鍵值對。不能是json格式
    • file是二進位制檔案
    • 如果url是https的話,加上verify=False。如果url是http的話,可不加。
import  requests
## --------------------------------------------------------------------
## 傳送post請求--帶引數(字典格式)
## --------------------------------------------------------------------
url1 = 'http://127.0.0.1/api/user/login'
data = {'username':'testuser1','passwd':'111111'}
res = requests.post(url1,data=data)#data可以直接傳字典
print('2.1=====',res)
print('2.2=====',res.json())#返回結果不需要decode,也可以直接通過json()轉成字典
print('2.3=====',res.text)
傳送post請求--帶引數
import  requests
## --------------------------------------------------------------------
## 傳送post請求--帶引數(json格式)
## --------------------------------------------------------------------
url3= 'http://127.0.0.1/api/user/add_stu'
data = {"name":"request_name","grade":"3","sex":"","age":28,"addr":"河南省"}
res = requests.post(url3,json=data)#注意,這裡的data是字典格式!之所以json=data,是因為請求報文要求入參是json格式,requests模組會自己將data字典轉成json格式再發送請求
print('3.1=====',res)
print('3.2=====',res.json())
print('3.3=====',res.text)

傳送post請求--帶cookie(僅字典格式)

import  requests
#獲取cookie值
url= 'http://127.0.0.1/api/user/login'
data = {'username':'testuser1','passwd':'111111'}
res = requests.post(url,data=data)
result = res.json()
print('4.0=====',result)
sign = result.get('login_info').get('sign')
## --------------------------------------------------------------------
## 傳送cookie
## --------------------------------------------------------------------
url4= 'http://127.0.0.1/api/user/gold_add'
data = {'stu_id':15,'gold':1000}
cookie ={'testuser1':sign}
res = requests.post(url4,data=data ,cookies=cookie)#data是字典
print('4.1=====',res)
print('4.2=====',res.json())
print('4.2=====',res.text)

傳送post請求--帶header(僅字典格式)

cookie如果有很多鍵值對的話,可以包裝在header裡發出,header={'Cookie':'a=v,b=v........'}

import  requests
## --------------------------------------------------------------------
## 傳送header
## --------------------------------------------------------------------
url5 = 'http://127.0.0.1/api/user/all_stu'
header = {'Referer':'http://api.nnzhp.cn/'}
res = requests.get(url5,headers=header)#傳header
print('5.1=====',res)
print('5.2=====',res.json())
print('5.3=====',res.text)
res = requests.get(url5)#不傳header
print('5.4=====',res.json())
requests.get(url,headers={'cookie':'pt2gguin=o0511402865; RK=JQZpwBp1by; '
                                   'ptcz=6c30e26a9ed6be93d3de9e4c4aca3e55650cf99fcffa64729bd1d58a5fb209d9; '
                                   'pgv_pvi=779236352; pgv_pvid=6970909788; qb_qua=; qb_guid=818de686e29d412fa4ee9e99905ea166; '
                                   'Q-H5-GUID=818de686e29d412fa4ee9e99905ea166; NetType=; pgv_si=s4499960832; '
                                   'FTN5K=0138ca95; pgv_info=ssid=s4269564370; luin=o0511402865; uin=o0511402865; '
                                   'lskey=00010000efc2701412d3429029ac9366e4ba98f0e978e0ae4a9c684101a7b22df0695f534bc242c8d4ff386d; '
                                   '[email protected]; ptisp=cnc; p_uin=o0511402865; pt4_token=wGU2YAaM0uu7LbcNjuDcLN-TPrEy7AZw4gcL5TEcKxw_; '
                                   'p_skey=1zg7yvF5wr6l43mfr-BvNHxuVDtybKpR5RbCrgC8weQ_'})#cookie傳入,直接拷貝進去


requests.get(url,cookies={'pt2ggui':'o0511402865','RK':'JQZpwBp1by'})#寫cookie的話,要一個個按照字典的方式寫

傳送post請求--帶file(僅二進位制格式)

r = requests.post(url,
                  data={'session_id':'6ab8785039dcf50fb11c53acc1db7648'},
                  files={'file_name':open('account.xls','rb')  }
                  )
import requests
## --------------------------------------------------------------------
## 上傳檔案
## --------------------------------------------------------------------
url7 = 'http://127.0.0.1/api/file/file_upload'
data = {'file':open('魔鬼中的天使.mp3','rb')}
res = requests.post(url7,files=data)#如果是https的話,要加上verfiy=False引數
print('3.1=====',res.json())

獲取響應結果

  • res  #返回如<Response [200]>
  • res.status_code  #返回狀態碼,如200
複製程式碼
1 import requests
2 ## --------------------------------------------------------------------
3 ## 返回狀態碼
4 ## --------------------------------------------------------------------
5 url = 'http://www.nnzhp.cn'
6 res = requests.get(url)#傳送get請求
7 print('1.1======',res.status_code)#獲取狀態碼
複製程式碼

 

1 1.1====== 200

 

  • res.json()  #返回字典。不需要手動decode()轉碼。如果res結果是json格式,可以使用json()將json串轉成字典格式。如果res結果不是json的話,不能使用json()

  • res.text #返回字串,響應的原始碼。不能用於下載檔案。

  • res.content  #返回二進位制。主要用於流媒體檔案、圖片檔案的下載。

下載mp3

import requests
## --------------------------------------------------------------------
## 返回二進位制--流媒體
## --------------------------------------------------------------------
url6 = 'http://qiniuuwmp3.changba.com/1084511584.mp3'
res = requests.get(url6)
with open('魔鬼中的天使.mp3','wb') as fw:#把二進位制檔案下載下來,寫入到'魔鬼中的天使.mp3'
    fw.write(res.content)#res.content返回結果是二進位制的,如x03\xe3\xa3\xf2......

下載圖片

import requests
## --------------------------------------------------------------------
## 返回二進位制--圖片
## --------------------------------------------------------------------
url7 = 'https://aliimg.changba.com/cache/photo/855e5493-f018-44db-8892-c8660649327b_640_640.jpg'
res = requests.get(url7,verify=False)#如果是https的話,要加上verfiy=False引數
print('3.3=====',res.content)#返回結果是二進位制的
with open('photo.jpg','wb') as fw:#把二進位制檔案下載下來,寫入到'photo.jpg'
    fw.write(res.content)

res.headers  #返回響應的所有headers

## --------------------------------------------------------------------
## 返回headers
## --------------------------------------------------------------------
url = 'http://www.nnzhp.cn'
res = requests.get(url)#傳送get請求
print('1.1======',res.headers)#獲取所有cookies

res.cookies  #返回響應的所有cookies

import requests
## --------------------------------------------------------------------
## 返回cookie
## --------------------------------------------------------------------
url = 'http://www.nnzhp.cn'
res = requests.get(url)#傳送get請求
print('1.1======',res.cookies)#獲取所有cookies