How to make cookies automatically obtain and expire automatically
This time I will show you how to automatically obtain cookies and automatically update them upon expiration. What are the precautions for automatically obtaining and automatically updating cookies upon 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/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 onlineUse selenium + PhantomJS to simulate browser login and get 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_dict2, get cookies from filesTraverse 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_dict3, 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_dict4, Request 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: ##How jQuery+koa2 implements Ajax requests
The above is the detailed content of How to make cookies automatically obtain and expire automatically. For more information, please follow other related articles on the PHP Chinese website!

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version
Chinese version, very easy to use

SublimeText3 Linux new version
SublimeText3 Linux latest version
