python爬虫用request库处理cookie的实例讲解
作者:宋雪维 时间:2023-07-26 03:57:53
python爬虫中使用urli库可以使用opener"发送多个请求,这些请求是能共享处理cookie的,小编之前也提过python爬虫中使用request库会比urllib库更加⽅便,使用使用requests也能达到共享cookie的目的,即使用request库get方法和使用requests库提供的session对象都可以处理。
方法一:使用request库get方法
resp = requests.get('http://www.baidu.com/')
print(resp.cookies)
print(resp.cookies.get_dict())
方法二:使用requests库提供的 session对象
import requests
url = "http://www.renren.com/PLogin.do"
data = {"email":"970138074@qq.com",'password':"pythonspider"}
headers = { 'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36" }
#登录
session = requests.session() session.post(url,data=data,headers=headers)
#访问
resp = session.get('http://www.renren.com/256450404/profile')
print(resp.text) ```
知识点扩展:
我们知道了requests中的session对象能够在请求之间保持cookie,它极大地方便了我们去使用cookie。当我们想设置方法级别中的请求时,可以如下面示例一样操作。
import requests
s = requests.session()
# 第一步:发送一个请求,用于设置请求中的cookies
cookies = dict(cookies_are='cookie1')
# tips: http://httpbin.org能够用于测试http请求和响应
r1 = s.get(url='http://httpbin.org/cookies', cookies=cookies)
print(r1.text)
# 第二步:发送一个请求,用于再次设置请求中的cookies
cookies = dict(cookies_are='cookie2')
r2 = s.get(url='http://httpbin.org/cookies', cookies=cookies)
print(r2.text)
运行后
# r1.text
{
"cookies": {
"cookies_are": "cookie1"
}
}
# t2.text
{
"cookies": {
"cookies_are": "cookie2"
}
}
来源:https://www.py.cn/spider/guide/25143.html
标签:python爬虫,request,cookie
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
javascript判断中文的正则
2024-04-10 10:56:27
SQLSERVER数据库升级脚本图文步骤
2024-01-27 10:20:26
![](https://img.aspxhome.com/file/2023/6/113556_0s.jpg)
给网站界面预留退路
2009-03-25 20:32:00
![](https://img.aspxhome.com/file/UploadPic/20093/25/01-11s.jpg)
Go语言底层原理互斥锁的实现原理
2024-04-25 15:00:24
![](https://img.aspxhome.com/file/2023/4/134274_0s.png)
Vue $emit()不能触发父组件方法的原因及解决
2024-05-28 16:10:26
详解OpenCV中直方图,掩膜和直方图均衡化的实现
2022-10-30 12:03:33
![](https://img.aspxhome.com/file/2023/8/107558_0s.jpg)
IE浏览器兼容Firefox的JS脚本的代码
2024-04-10 13:58:15
Python闭包实现计数器的方法
2021-01-23 09:11:00
js放大缩小容器:仿动画
2008-02-15 11:34:00
asp自动采集程序
2009-02-04 10:11:00
python多进程提取处理大量文本的关键词方法
2022-02-17 13:07:36
![](https://img.aspxhome.com/file/2023/7/67837_0s.jpg)
Python-while 计算100以内奇数和的方法
2022-03-24 12:00:39
Python基础之字符串操作常用函数集合
2023-11-26 23:26:12
![](https://img.aspxhome.com/file/2023/9/87739_0s.png)
对python字典元素的添加与修改方法详解
2023-10-19 09:36:04
实例解析Python中的__new__特殊方法
2023-01-09 22:26:19
使用Python3+PyQT5+Pyserial 实现简单的串口工具方法
2021-09-09 16:49:42
![](https://img.aspxhome.com/file/2023/6/91896_0s.jpg)
Qt5 实现主窗口状态栏显示时间
2022-05-29 23:54:45
![](https://img.aspxhome.com/file/2023/0/102340_0s.jpg)
浅谈MySQL timestamp(3)问题
2024-01-14 17:47:23
![](https://img.aspxhome.com/file/2023/9/105679_0s.png)
一步步教你配置MySQL远程访问
2024-01-16 13:07:26
![](https://img.aspxhome.com/file/2023/1/68061_0s.png)
Python使用内置函数setattr设置对象的属性值
2021-10-09 20:32:44