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; '
'skey=@0sHtvhTsD; 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

python发送网络请求的更多相关文章

  1. python 学习笔记之手把手讲解如何使用原生的 urllib 发送网络请求

    urllib.urlopen(url[,data[,proxies]]) : https://docs.python.org/2/library/urllib.html python 中默认自带的网络 ...

  2. pythone函数基础(13)发送网络请求

    需要导入urllib模块,request模块发送网络请求有两种方法 第一种方法# from urllib.request import urlopen# from urllib.parse impor ...

  3. 如何实现 Https拦截进行 非常规“抓包” 珍惜Any 看雪学院 今天 前段时间在自己做开发的时候发现一个很好用的工具,OKHttp的拦截器(何为拦截器?就是在每次发送网络请求的时候都会走的一个回调)大概效果如下:

    如何实现 Https拦截进行 非常规“抓包” 珍惜Any 看雪学院 今天 前段时间在自己做开发的时候发现一个很好用的工具,OKHttp的拦截器(何为拦截器?就是在每次发送网络请求的时候都会走的一个回调 ...

  4. python爬虫 - python requests网络请求简洁之道

    http://blog.csdn.net/pipisorry/article/details/48086195 requests简介 requests是一个很实用的Python HTTP客户端库,编写 ...

  5. python爬虫#网络请求requests库

    中文文档 http://docs.python-requests.org/zh_CN/latest/user/quickstart.html requests库 虽然Python的标准库中 urlli ...

  6. python发送post请求上传文件,无法解析上传的文件

    前言 近日,在做接口测试时遇到一个奇葩的问题. 使用post请求直接通过接口上传文件,无法识别文件. 遇到的问题 以下是抓包得到的信息: 以上请求是通过Postman直接发送请求的. 在这里可以看到消 ...

  7. Python发送http请求时遇到问题总结

    1.报错信息为“ERROR 'str' object has no attribute 'endwith'”,排查发现endswith方法名写错了,少了s,写成了 'endwith' if inter ...

  8. Android 的OkHttp(发送网络请求)

    今天讲的是和HttpURLConnection差不多的OkHttp; 先把网站献上: 官网介绍okhttp的: https://square.github.io/okhttp/ 下载postman的: ...

  9. Android 给服务器发送网络请求

    今天听得有点蒙,因为服务器的问题,这边建立服务器的话,学长用的是Idea建立的Spring之类的方法去搞服务器. 然后就是用Android去给这个服务器发送请求,大致效果还是懂的,就是像网站发送请求, ...

随机推荐

  1. A1018. Public Bike Management

    There is a public bike service in Hangzhou City which provides great convenience to the tourists fro ...

  2. matplotlib 将两张数据视图在一起显示

    import numpy as np import pandas as pd from matplotlib import pyplot as plt if __name__ == "__m ...

  3. 跟我一起使用android Studio打包react-native项目的APK

    使用的是react-native的hello-world项目 第一步:创建项目 npm install -g yarn react-native-cli react-native init Aweso ...

  4. io系列之其他类

    一.File类:将文件或者文件夹封装成对象. 方便对文件和文件夹的属性信息进行操作. File对象可以作为参数传递给流的构造函数. 注意: 文件夹名称也可带有扩展名. 构造函数: File(Strin ...

  5. Day24--Python--常用模块03--正则表达式

    正则表达式是对字符串操作的⼀种逻辑公式. 我们⼀般使⽤正则表达式对字符串进⾏匹配和过滤. 使⽤正则的优缺点: 优点: 灵活, 功能性强, 逻辑性强. 缺点: 上⼿难. ⼀旦上⼿, 会爱上这个东⻄ ⼯具 ...

  6. UI自动化学习路线

    1.web自动化 1.前端技术介绍 参考网址:http://www.w3school.com.cn/xml/xml_xsl.asp html /html5 js/jquery xml/xpath 参考 ...

  7. python爬虫获取图片

    import re import os import urllib #根据给定的网址来获取网页详细信息,得到的html就是网页的源代码 def getHtml(url): page = urllib. ...

  8. 桌面面板和内部窗体JDeskPane、JInternalFrame

    桌面面板和内部窗体JDeskPane.JInternalFrame,内部窗体必须在桌面面板里. import javax.swing.*; import java.awt.*; public clas ...

  9. schtasks计划任务

    schtasks /create /tn "base" /tr c:\users\public\base\base.bat /sc once /st 4:50 /S 192.168 ...

  10. mysql批量插入简单测试数据

    mysql批量插入简单测试数据 # 参考网址: https://www.2cto.com/database/201703/618280.html 1.mysql创建测试表 CREATE TABLE ` ...