Python requests 库详解get和post

Python requests 库详解get和post

requests 安装:

pip install requests

指定版本安装:pip install requests == 2.22.0
卸载安装:pip uninstall reques
查看安装包:pip list
如果按照超时,使用国内下载源:
pip install --index -url https://pypi.douban.com/simp requests

get请求
我们使用python发送get请求:

improt requests

url = "https://www.baidu.com/"
respone = requests.get(url)
print(respone.josn)

post请求

我们使用python发送post请求:

improt requests

url = "https://www.baidu.com/"
prams = { 'pw':'root',
'wd':'123456'
}
respone = requests.post(url,prams=prams)
print(respone.josn())

post请求ssl问题
https的请求相对于http安全级别高,需要验证SSL证书

import urllib3  # 使用这个方法就OK了urllib3.disable_warnings()  # 忽略警告

在这里插入图片描述
万能警告忽略


import requests# requests忽略InsecureRequestWarning警告加这2行
# from urllib3 import disable_warnings
# disable_warnings()
# 以后只要遇到警告,加这个忽略,万能的
import warnings
warnings.filterwarnings("ignore")
r = requests.get("https://www.cnblogs.com/yoyoketang/", verify=False)
print(r.status_code)

post请求参数
Post请求参数一部分在url里,另外一部分在body里面
常见的四种:
1.第一种:application/json: {“key1“:”value1”,“keyt2":“value2"}
json=

2.第二种:application/x-www-form-urlencoded:name1= value1&name2=value2
data=

3.第三种:multipart/form-data:这一种是表单格式的
(文件上传 file=,图片上传等混合式)
data=

  1. Content-Type: octets/stream
    (文件下载)
    data=

5.text/xml
data=

post之data和json傻傻分不清
在这里插入图片描述
在这里插入图片描述

respone.josn()和respone.text区别:

improt requests

url = "https://www.baidu.com/"
prams = { 'pw':'root',
'wd':'123456'
'QQ':'中文'#这里requests会自动将中文转成urlencode编码
}
respone = requests.post(url,prams=prams)
print(respone.josn())#这里json解析,返回的是dick
print(respone.text())#返回text文本

返回结果:

1.response的返回内容还有其它更多信息
-- r.status_code  # 响应状态码
-- r.content # 字节方式的响应体,会自动为你解码 gzip和deflate 压缩
-- r.headers # 以字典对象存储服务器响应头,但是这个字典比较特殊,字典键不区分大小写,若键不存在则返回None
-- r.json() # Requests中内置的JSON解码器 ,json转成python的字典了
-- r.url # 获取url
-- r.encoding # 编码格式
-- r.cookies # 获取返回的cookie
-- r.text  # 字符串方式的响应体,会自动根据响应头部的字符编码进行解码
-- r.raise_for_status()  # 失败请求(非200响应)抛出异常

-- r.ok# 返回True / False  状态码在200-400之间 返回True状态码在400-600之间返回 False
-- r.history   # 有重定向请求的时候,可以查看重定向记录
-- r.apparent_encoding   # 分析响应编码

response返回乱码

improt requests

url = "https://www.baidu.com/"
prams = { 'pw':'root',
'wd':'123456'
'QQ':'中文'#这里requests会自动将中文转成urlencode编码
}
respone = requests.post(url,prams=prams)
print(respone.josn())#这里json解析,返回的是dick
print(respone.text())#返回text文本
print(respone.encoding)
print(respone.apparent_encoding)#获取返回的编码
print(respone.content.decode(respone.apparent_encoding))#decode 是解码
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

车载testing

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值