python爬虫获取cookie
时间: 2023-12-02 07:03:21 浏览: 160
以下是两种Python爬虫获取cookie的方法:
1. 利用requests库获取cookie
```python
import requests
# 发送登录请求,获取cookie
login_url = 'http://www.example.com/login'
data = {'username': 'your_username', 'password': 'your_password'}
response = requests.post(login_url, data=data)
cookie = response.cookies.get_dict()
# 使用cookie发送其他请求
other_url = 'http://www.example.com/other'
response = requests.get(other_url, cookies=cookie)
```
2. 模拟登录获取cookie
```python
import requests
from PIL import Image
from io import BytesIO
# 获取验证码图片
captcha_url = 'http://www.example.com/captcha'
response = requests.get(captcha_url)
captcha_img = Image.open(BytesIO(response.content))
captcha_img.show()
# 输入验证码并发送登录请求,获取cookie
login_url = 'http://www.example.com/login'
data = {'username': 'your_username', 'password': 'your_password', 'captcha': input('请输入验证码:')}
response = requests.post(login_url, data=data)
cookie = response.cookies.get_dict()
# 使用cookie发送其他请求
other_url = 'http://www.example.com/other'
response = requests.get(other_url, cookies=cookie)
```
阅读全文
相关推荐















