requests库的了解使用

第一部分第二部分
基本操作高级操作
1-91-7

基本操作

1.各种请求方式
get、post、put、delete、head、options
网址:http://httpbin.org/get
2.响应请求
response = requests.get("www.baidu.com")  请求百度信息
print(response.status_code)	状态码
print(response.text)		响应内容
print(response.cookies)		登录信息
3.带参数的请求
response = requests.get("http://www.baidu.com/get?name=joy&age=22")		
这种写法较为繁琐,可改为使用字典。
4.使用参数字典的请求
data = {'name':'joy',
	'age':'19'}
response = requests.get("www.baidu.com", params=data)
print(response.text)
5.获取解析json数据
import requests	导包
import json
response = requests.get("www.baidu.com")
print(response.json)	效果等同于 print(json.load(response.text))
这样就可以使用字典来取出你需要的数据
6.获取二进制数据
response = requests.get("www.baidu.com")
print(response.content)
7.保存数据
response = requests.get("www.baidu.com")
with open('localtion.html','wb') as f:		b表示二进制数据
	f.write(response.content)
	f.close
8.添加headers伪装
heades = {}
	模拟谷歌:进入浏览器,右键点击检查,进入Network,然后进入Headers,复制其信息
response =requests.get("www.baidu.com", headers=headers)
print(response.status_code)	  状态码200为正常
9.状态码判断
response = requests.get("www.baidu.com")
exit() if not response.status_code == 200 else print("Request Successfuily")

高级操作

1.文件上传
files = {'file':  open('图片二进制信息', 'rb')}
response = requests.post('http://httpbin.org/post',files=files)
print(response.content)
2.回话维持
s = requests.Session()
s.get("http://httpbin.org/cookies/number/123123")
response = s.get("http://httpbin.org/cookies")
print(response.text)
可以得到:
	{"cookies": {"number": "123123"}}
3.获取cookies
response = requests.get("www.baidu.com")
for k,v in response.cookies.items():
	print(k + "=" + v)
4.设置代理
proxies = {
	"http": "http://127.0.0.1:3306",
	"http": "http://user:password@127.0.0.1:3306"
}
response = requests.get("www.baidu.com", proxies=proxies)
print(response.status_code)
5.超时设置
response = requests.get("www.baidu.com", timeout=1)
print(response.status_code)
6.认证设置
response = requests.get("www.baidu.com", auth=('root','123456'))
print(response.status_code)
7.异常处理
import requests
from requests.exception import ReadTimeout,ConnectionError,RequestException
try:
	response = requests.get("www.baidu.com", timeout=1)
	print(response.status_code)
except ReadTimeout:
	print("超时")
except ConnectionError:
	print("网络错误")	
except RequestException:
	print("出错")
先捕获子类异常,再捕获父类异常,可清晰分析错误地方
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

hao难懂

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

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

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

打赏作者

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

抵扣说明:

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

余额充值