


Automatic acquisition and expiration of cookies through web crawlers (detailed tutorial)
This article mainly introduces the implementation method of automatic acquisition of cookies and automatic update of expired cookies by web crawlers. Friends in need can refer to the following
This article implements automatic acquisition of cookies and automatic update of cookies when expired.
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 with the .weibo suffix. document.
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, Use cookies to request other Weibo homepages
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 解析网页 ...
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
How to use v-for in vue to traverse a two-dimensional array
Data of v-for in Vue Grouping instance
vue2.0 computed instance of calculating the accumulated value after list loop
The above is the detailed content of Automatic acquisition and expiration of cookies through web crawlers (detailed tutorial). For more information, please follow other related articles on the PHP Chinese website!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Cookies are usually stored in the cookie folder of the browser. Cookie files in the browser are usually stored in binary or SQLite format. If you open the cookie file directly, you may see some garbled or unreadable content, so it is best to use Use the cookie management interface provided by your browser to view and manage cookies.

Cookies on your computer are stored in specific locations on your browser, depending on the browser and operating system used: 1. Google Chrome, stored in C:\Users\YourUsername\AppData\Local\Google\Chrome\User Data\Default \Cookies etc.

Cookies on the mobile phone are stored in the browser application of the mobile device: 1. On iOS devices, Cookies are stored in Settings -> Safari -> Advanced -> Website Data of the Safari browser; 2. On Android devices, Cookies Stored in Settings -> Site settings -> Cookies of Chrome browser, etc.

Preface: vim is a powerful text editing tool, which is very popular on Linux. Recently, I encountered a strange problem when using vim on another server: when I copied and pasted a locally written script into a blank file on the server, automatic indentation occurred. To use a simple example, the script I wrote locally is as follows: aaabbbcccddd. When I copy the above content and paste it into a blank file on the server, what I get is: aabbbcccddd. Obviously, this is what vim does automatically for us. Format indentation. However, this automatic is a bit unintelligent. Record the solution here. Solution: Set the .vimrc configuration file in our home directory, new

The working principle of cookies involves the server sending cookies, the browser storing cookies, and the browser processing and storing cookies. Detailed introduction: 1. The server sends a cookie, and the server sends an HTTP response header containing the cookie to the browser. This cookie contains some information, such as the user's identity authentication, preferences, or shopping cart contents. After the browser receives this cookie, it will be stored on the user's computer; 2. The browser stores cookies, etc.

The dangers of cookie leakage include theft of personal identity information, tracking of personal online behavior, and account theft. Detailed introduction: 1. Personal identity information is stolen, such as name, email address, phone number, etc. This information may be used by criminals to carry out identity theft, fraud and other illegal activities; 2. Personal online behavior is tracked and analyzed through cookies With the data in the account, criminals can learn about the user's browsing history, shopping preferences, hobbies, etc.; 3. The account is stolen, bypassing login verification, directly accessing the user's account, etc.

If you are using a Linux operating system and want the system to automatically mount the drive on boot, you can do this by adding the device's unique identifier (UID) and mount point path to the fstab configuration file. fstab is a file system table file located in the /etc directory. It contains information about the file systems that need to be mounted when the system starts. By editing the fstab file, you can ensure that the required drives are loaded correctly every time the system starts, thus ensuring stable system operation. Automatically mounting drivers can be conveniently used in a variety of situations. For example, I plan to back up my system to an external storage device. To achieve automation, ensure that the device remains connected to the system, even at startup. Likewise, many applications will directly

The effects of clearing cookies include resetting personalization settings and preferences, affecting ad experience, and destroying login status and password remembering functions. Detailed introduction: 1. Reset personalized settings and preferences. If cookies are cleared, the shopping cart will be reset to empty and products need to be re-added. Clearing cookies will also cause the login status on social media platforms to be lost, requiring re-adding. Enter your username and password; 2. It affects the advertising experience. If cookies are cleared, the website will not be able to understand our interests and preferences, and will display irrelevant ads, etc.
