search
HomeWeb Front-endJS TutorialSet cookie expiration to automatically update and automatically obtain

This time I will introduce to you the settings for automatic update and automatic acquisition of cookie expiration. What are the precautions for setting automatic update and automatic acquisition of cookie expiration? The following is a practical case, let's take a look.

This article implements automatic acquisition of cookies and automatic update of cookies when they expire.

A lot of information on social networking sites requires logging in to get it. Take Weibo as an example. Without logging in, you can only see the top ten Weibo posts of big Vs. To stay logged in, cookies are required. Take logging in to www.weibo.cn as an example:

Enter in chrome: http://login.weibo.cn/login/

Analysis Control When the header request from the station is returned, you will see several sets of cookies returned by weibo.cn.

Implementation steps:

1, use selenium to automatically log in to obtain cookies, save them to a file;

2, read cookie, compare the validity period of the cookie, and if it expires, perform step 1 again;

3, when requesting other web pages, fill in the cookie to maintain the login status.

1, Get cookies online

Use selenium + PhantomJS to simulate browser login and obtain cookies;

There are usually multiple cookies, and the cookies are stored one by one in .weibo suffix file.

def get_cookie_from_network():
 from selenium import webdriver
 url_login = 'http://login.weibo.cn/login/' 
 driver = webdriver.PhantomJS()
 driver.get(url_login)
 driver.find_element_by_xpath('//input[@type="text"]').send_keys('your_weibo_accout') # 改成你的微博账号
 driver.find_element_by_xpath('//input[@type="password"]').send_keys('your_weibo_password') # 改成你的微博密码
 driver.find_element_by_xpath('//input[@type="submit"]').click() # 点击登录
 # 获得 cookie信息
 cookie_list = driver.get_cookies()
 print cookie_list
 cookie_dict = {}
 for cookie in cookie_list:
  #写入文件
  f = open(cookie['name']+'.weibo','w')
  pickle.dump(cookie, f)
  f.close()
  if cookie.has_key('name') and cookie.has_key('value'):
   cookie_dict[cookie['name']] = cookie['value']
 return cookie_dict
2, get cookies from files

Traverse files ending with .weibo, that is, cookie files, from the current directory. Use pickle to unpack it into a dict, compare the expiry value with the current time, and return empty if it expires;

def get_cookie_from_cache():
 cookie_dict = {}
 for parent, dirnames, filenames in os.walk('./'):
  for filename in filenames:
   if filename.endswith('.weibo'):
    print filename
    with open(self.dir_temp + filename, 'r') as f:
     d = pickle.load(f)
     if d.has_key('name') and d.has_key('value') and d.has_key('expiry'):
      expiry_date = int(d['expiry'])
      if expiry_date > (int)(time.time()):
       cookie_dict[d['name']] = d['value']
      else:
       return {}
 return cookie_dict
3, if the cached cookie expires, obtain the cookie from the network again

def get_cookie():
 cookie_dict = get_cookie_from_cache()
 if not cookie_dict:
  cookie_dict = get_cookie_from_network()
 return cookie_dict
4, Requesting other Weibo homepages with cookies

def get_weibo_list(self, user_id):
 import requests
 from bs4 import BeautifulSoup as bs
 cookdic = get_cookie()
 url = 'http://weibo.cn/stocknews88' 
 headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36'}
 timeout = 5
 r = requests.get(url, headers=headers, cookies=cookdic,timeout=timeout)
 soup = bs(r.text, 'lxml')
 ...
 # 用BeautifulSoup 解析网页
 ...
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

react native uses fetch to upload images

How to compress the files packaged by webpack to become smaller

Use import and require to package JS

##The Starry Navigation Bar Special Effect

The above is the detailed content of Set cookie expiration to automatically update and automatically obtain. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
修复:谷歌浏览器请求太多错误 429 [已解决]修复:谷歌浏览器请求太多错误 429 [已解决]Apr 16, 2023 am 09:22 AM

近期很多Windows用户反映,当他们尝试访问某个URL时,PC上的GoogleChrome浏览器显示错误429。这是因为每次用户尝试在短时间内通过浏览器。通常,此错误是由网站生成的,以避免通过向服务器发送过多请求而被机器人或黑客入侵病毒。用户对在这个阶段可以做什么感到困惑,并因此感到失望。导致此错误的因素可能很多,我们在下面列出了其中一些因素。缓存内存和其他站点数据未清除从第三方来源安装的扩展系统上的一些有害软件病毒攻击在研究了上面列出的因素之后,我们在这篇文章中收集了一些修复程序,这

如果 Grammarly 无法在 Windows 10 浏览器上运行的 8 个重大修复如果 Grammarly 无法在 Windows 10 浏览器上运行的 8 个重大修复May 05, 2023 pm 02:16 PM

如果您在Windows10或11PC上遇到语法问题,本文将帮助您解决此问题。Grammarly是最流行的打字助手之一,用于修复语法、拼写、清晰度等。它已经成为写作专业人士必不可少的一部分。但是,如果它不能正常工作,它可能是一个非常令人沮丧的体验。许多Windows用户报告说此工具在他们的计算机上运行不佳。我们做了深入的分析,找到了这个问题的原因和解决方案。为什么Grammarly无法在我的PC上运行?由于几个常见原因,PC上的Grammarly可能无法正常工作。它包括以下内

如何修复 Google Chrome 上的 Roblox 403 禁止错误如何修复 Google Chrome 上的 Roblox 403 禁止错误May 19, 2023 pm 01:49 PM

许多Windows用户最近在尝试访问GoogleChrome浏览器中的网站URL时遇到了一个不寻常的错误,称为Roblox403禁止错误。即使在多次重新启动Chrome应用程序后,他们也无能为力。此错误可能有几个潜在原因,我们在下面概述并列出了其中一些。Chrome的浏览历史和其他缓存以及损坏的数据不稳定的互联网连接网站网址不正确从第三方来源安装的扩展在考虑了上述所有方面之后,我们提出了一些修复程序,可以帮助用户解决此问题。如果您遇到同样的问题,请查看本文中的解决方案。修复1

vue3中cookie如何使用vue3中cookie如何使用May 12, 2023 pm 02:19 PM

前言cookie使用最多的地方想必是保存用户的账号与密码,可以避免用户每次登录时都要重新输入1.vue中cookie的安装在终端中输入命令npminstallvue-cookies--save,即可安装cookies,安装之后在main.js文件中写下以下代码import{createApp}from'vue'importVueCookiesfrom'vue-cookies'constapp=createApp(App)app.co

如何在 Google Chrome 中启用或禁用第三方 Cookie如何在 Google Chrome 中启用或禁用第三方 CookieApr 15, 2023 pm 02:07 PM

每个网站都通过创建cookie使用户更容易浏览他们的网页和浏览他们的网站。然而,网站创建了一些第三方cookie,使他们能够跟踪访问其他网站的用户,以便更好地了解他们,从而有助于展示广告和其他帖子。一些用户可能认为他们的数据遭到破坏或存在安全风险,而另一些用户可能认为允许这些第三方cookie跟踪他们以在浏览器上获取更多内容是很好的。所以我们在这篇文章中解释了如何在谷歌浏览器中启用或禁用第三方cookies,详细步骤如下。如何在GoogleChrome中启用第三方Cookie如果您认为要

PHP8.0中的Cookie库PHP8.0中的Cookie库May 14, 2023 pm 04:51 PM

在互联网应用开发中,使用Cookie是常见的一种方式来维护用户会话状态。在PHP语言中,处理Cookie的相关功能在语言的核心库中得到了完善的支持,在最新的PHP8.0版本中,Cookie库得到了进一步的增强。一、PHP中的CookieCookie是一个小文本文件,可以存储在用户的浏览器中,它通常被用来记录用户的个性化设置、登录状态等信息。Cookie是基

php curl怎么设置cookiephp curl怎么设置cookieSep 26, 2021 am 09:27 AM

php curl设置cookie的方法:1、创建PHP示例文件;2、通过“curl_setopt”函数设置cURL传输选项;3、在CURL中传递cookie即可。

如何在ThinkPHP6中使用Cookie技术实现记住我功能如何在ThinkPHP6中使用Cookie技术实现记住我功能Jun 20, 2023 pm 03:33 PM

随着互联网技术的不断发展,越来越多的网站需要用户登录才能使用其功能。但是每次用户访问时都需要输入账号密码显然很不方便,因此“记住我”的功能应运而生。本文将介绍如何在ThinkPHP6中采用Cookie技术实现记住我功能。一、Cookie简介Cookie是一种服务器向客户端发送的小文件,在用户访问网站时存储在用户的计算机上。这些文件包含与用户相关的信息,如登录

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor