requests模块基础知识

本文介绍了Python的requests模块,包括基本用法、GET和POST请求的发送、JSON解析、二进制文件保存、设置HTTP头、使用代理、管理cookie以及会话维持和超时异常处理等核心功能。
摘要由CSDN通过智能技术生成

基本用法:

response = requests.get(url)
response.status_code #状态码
response.url #请求的url
response.headers #头消息
response.cookies  #cookies信息
response.text #网页源码
response.content #以字节流方式查看网页源码

各种请求方式:

requests.get
requests.post
requests.put
requests.delete
requests.head
requests.options

get请求:

1、将参数直接放在url内:
	response = requests.get(url?name='zhangsan')
2、先将参数填在dict内,发起请求时params参数指定为dict
	data = {'name':'zhangsan'}
	response = requests.get(url,params = data)

POST请求:

	data = {'name':'zhangsan'}
	response = requests.post(url,data = data)

解析Json

response.json()     方法同json.loads(response.text)
type(response.json())
<class 'dict'>

简单保存二进制文件:

二进制内容为response.content
with open(file,'wb') as f:
	f.write(response.content)

填写头信息:

heads = {}
heads['User-Agent'] = 'xxxxxxxxxxx'
xxxxxxxxxx = xxxxxxxxxx
requests.get(URL,headers = heads)

使用代理:

1、使用普通代理
	同添加头方法,代理参数也是dict
	proxy = {
					'http':'1234578090'
		}
	requests.get(URL,proxies = proxy)
2、使用socks代理
	安装socks包
	pip install requests[socks]
	然后定义proxy字典。方法同

获取cookie

response.cookies
for k,v in response.cookies:
	print(k+':'v)

BDORZ:12345

会话维持:

	res = requests.Session() 
	res作为requests库中的Session对象,该对象登陆成功后,以后用该对象访问,都是以同cookies登录
	
session:指从打开一个网站开始,到关闭浏览器一系列请求过程,会话有一定生命周期,当长时间或者超过有效期没有访问网站,或者关闭浏览器,服务器会删除该数据,因为HTTP协议是无状态协议,没有记忆性,下次访问时需要重新传递数据。
	cookie:指网站为了辨别用户身份进行会话而储存在本地的数据,一般以文本形式存在本地电脑,cookie是由键值对组成的。

超时异常捕获

from requests.exceptions import ReadTimeout
try:
	res = requests.get(URL,timeout = 秒)
except ReadTimeout:
	pass
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值