在Python的爬虫库requests中处理Cookie非常简单。当你在发送请求时,可以通过设置cookies
参数来添加或传递Cookie。以下是一些处理Cookie的常见方法:
import requests
url = 'https://example.com'
cookies = {
'cookie_name': 'cookie_value',
'another_cookie_name': 'another_cookie_value'
}
response = requests.get(url, cookies=cookies)
import requests
url = 'https://example.com'
response = requests.get(url)
cookies = response.cookies
print(cookies)
import requests
url = 'https://example.com'
cookies = {
'cookie_name': 'cookie_value',
'another_cookie_name': 'another_cookie_value'
}
# 发送第一个请求并获取响应
response1 = requests.get(url, cookies=cookies)
# 使用相同的Cookie发送第二个请求
response2 = requests.get(url, cookies=cookies)
requests.Session()
来保持会话并自动处理Cookie。import requests
url = 'https://example.com'
session = requests.Session()
# 设置Cookie
cookies = {
'cookie_name': 'cookie_value',
'another_cookie_name': 'another_cookie_value'
}
session.cookies.update(cookies)
# 发送请求
response = session.get(url)
通过这些方法,你可以轻松地在Python爬虫中使用requests库处理Cookie。