Python爬虫Cookie的使用场景登录后保存Cookie与加载

cookie的使用

网络部分信息或APP的信息,若是想获取数据时,需要提前做一些操作,往往是需要登录,或者提前访问过某些页面才可以获取到!!

其实底层就是在网页里面增加了Cookie信息

代码

from urllib.request import Request,build_opener
from fake_useragent import UserAgent


url ='https://www.kuaidaili.com/usercenter/overview'
headers = {
  'User-Agent':UserAgent().chrome,
  'Cookie':'channelid=0; sid=1621786217815170; _ga=GA1.2.301996636.1621786363; _gid=GA1.2.699625050.1621786363; Hm_lvt_7ed65b1cc4b810e9fd37959c9bb51b31=1621786363,1621823311; _gat=1; Hm_lpvt_7ed65b1cc4b810e9fd37959c9bb51b31=1621823382; sessionid=48cc80a5da3a451c2fa3ce682d29fde7'
}
req = Request(url,headers= headers)
opener = build_opener()
resp = opener.open(req)


print(resp.read().decode())

登录后保持cookie

image-20220517203932946

问题

不想手动复制cookie,太繁琐了!

解决方案

在再代码中执行登录操作,并保持Cookie不丢失

为了保持Cookie不丢失可以urllib.request.HTTPCookieProcessor来扩展opener的功能

代码

from urllib.request import Request,build_opener
from fake_useragent import UserAgent
from urllib.parse import urlencode
from urllib.request import HTTPCookieProcessor


login_url ='https://www.kuaidaili.com/login/'


args = {
  'username':'398707160@qq.com',
  'passwd':'123456abc'
}
headers = {
  'User-Agent':UserAgent().chrome
}
req = Request(login_url,headers= headers,data = urlencode(args).encode())
# 创建一个可以保存cookie的控制器对象
handler = HTTPCookieProcessor()
# 构造发送请求的对象
opener = build_opener(handler)
#  登录
resp = opener.open(req)


'''
-------------------------上面已经登录好----------------------------------
'''


index_url ='https://www.kuaidaili.com/usercenter/overview'
index_req = Request(index_url,headers =headers)
index_resp = opener.open(index_req)


print(index_resp.read().decode())

cookie的保存与加载

image-20220517203121060

1 原理

image-20220518104138154

2 CookieJar

我们可以利用本模块的http.cookiejar.CookieJar类的对象来捕获cookie并在后续连接请求时重新发送,比如可以实现模拟登录功能。该模块主要的对象有CookieJar、FileCookieJar、MozillaCookieJar、LWPCookieJar

from urllib.request import Request,build_opener,HTTPCookieProcessor
from fake_useragent import UserAgent
from urllib.parse import urlencode
from http.cookiejar import MozillaCookieJar

def get_cookie():
  url = 'https://www.kuaidaili.com/login/'
  args = {
    'username':'398707160@qq.com',
    'passwd':'123456abc'
   }
  headers = {'User-Agent':UserAgent().chrome}
  req = Request(url,headers = headers, data = urlencode(args).encode())

  cookie_jar = MozillaCookieJar()
  handler = HTTPCookieProcessor(cookie_jar)
  opener = build_opener(handler)
  resp = opener.open(req)
  # print(resp.read().decode())
  cookie_jar.save('cookie.txt',ignore_discard=True,ignore_expires=True)

def use_cookie():
  url = 'https://www.kuaidaili.com/usercenter/'
  headers = {'User-Agent':UserAgent().chrome}
  req = Request(url,headers = headers)
  
  cookie_jar = MozillaCookieJar()
  cookie_jar.load('cookie.txt',ignore_discard=True,ignore_expires=True)
  handler = HTTPCookieProcessor(cookie_jar)
  opener = build_opener(handler)
  resp = opener.open(req)
  print(resp.read().decode())


if __name__ == '__main__':
  # get_cookie()
  use_cookie()


  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Python 爬虫使用 cookie 登录,一般需要以下步骤: 1. 发送登录请求,获取登录成功后的 cookie。 2. 将 cookie 保存下来,后续请求时带上 cookie。 下面是一个示例代码,假设登录成功后返回的 cookie 存储在变量 `cookie_str` 中: ```python import requests # 登录请求的 URL 和参数 login_url = 'http://example.com/login' login_data = {'username': 'your_username', 'password': 'your_password'} # 发送登录请求 session = requests.Session() response = session.post(login_url, data=login_data) # 获取 cookie,转换为字典格式 cookies = requests.utils.dict_from_cookiejar(session.cookies) # 将 cookie 转换为字符串格式,用于保存到文件或数据库中 cookie_str = '; '.join([f'{key}={value}' for key, value in cookies.items()]) # 将 cookie 保存到文件中 with open('cookie.txt', 'w') as f: f.write(cookie_str) # 后续请求时带上 cookie headers = {'Cookie': cookie_str} response = requests.get('http://example.com/some_page', headers=headers) ``` 在后续的请求中,需要将 cookie 以字符串格式入到请求头部,示例代码中使用了 `headers` 参数来设置请求头部。如果需要从文件中读取保存cookie,可以使用以下代码: ```python # 从文件中读取 cookie with open('cookie.txt', 'r') as f: cookie_str = f.read().strip() # 将 cookie 以字典格式入到 session session = requests.Session() cookies = requests.utils.cookiejar_from_dict({cookie.split('=')[0]: cookie.split('=')[1] for cookie in cookie_str.split('; ')}) session.cookies.update(cookies) # 后续请求时带上 cookie headers = {'Cookie': cookie_str} response = session.get('http://example.com/some_page', headers=headers) ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

留不住的人

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

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

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

打赏作者

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

抵扣说明:

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

余额充值