Cat brother teach you to write reptile 042 - session usage

session and their usage

The so-called session, you can be understood as we use the Internet browser, close to the process browser.

is the session during the session, the server used to record information for a particular user session.

For example, you open the browser visiting the whole process of shopping pages, browse the merchandise which, in the shopping cart, the number of items,

These records will be stored in the server session.

If there is no session, so the situation may appear funny:

When you add a lot of merchandise purchased in the shopping cart, going to the settlement, we discovered cart empty Σ (っ ° Д °;) っ,

Because the server did not help you record you want to buy goods.

Relations session and cookies are also very close

cookies are stored with the encoded information session, session and stores information in the cookies

When the browser first visit shopping Web page, the server returns a field set cookies to the browser, the browser to save cookies to the local

And other browser second visit to this shopping website, will take cookies to the request,

cookies with encoded information in the session, the server can immediately identify the user, and returns the user session and relevant.

This is also why you shopping site each time you log in again before you put in the shopping cart of goods and not the cause of the disappearance.

Because you when you log in, the server can carry through the browser cookies, find the session you save shopping cart information.

import requests
#引用requests。
session = requests.session()
#用requests.session()创建session对象,相当于创建了一个特定的会话,帮我们自动保持了cookies。
url = 'https://wordpress-edu-3autumn.localprod.forc.work/wp-login.php'
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'
}
data = {
    'log':input('请输入账号:'), #用input函数填写账号和密码,这样代码更优雅,而不是直接把账号密码填上去。
    'pwd':input('请输入密码:'),
    'wp-submit':'登录',
    'redirect_to':'https://wordpress-edu-3autumn.localprod.forc.work/wp-admin/',
    'testcookie':'1'
}
session.post(url,headers=headers,data=data)
#在创建的session下用post发起登录请求,放入参数:请求登录的网址、请求头和登录参数。
url_1 = 'https://wordpress-edu-3autumn.localprod.forc.work/wp-comments-post.php'
#把我们想要评论的文章网址赋值给url_1。
data_1 = {
'comment': input('请输入你想要发表的评论:'),
'submit': '发表评论',
'comment_post_ID': '13',
'comment_parent': '0'
}
#把有关评论的参数封装成字典。
comment = session.post(url_1,headers=headers,data=data_1)
#在创建的session下用post发起评论请求,放入参数:文章网址,请求头和评论参数,并赋值给comment。
print(comment)
#打印comment
复制代码

Use requests.session (), you do not consider cookies in question

Storing cookies

import requests
session = requests.session()
url = 'https://wordpress-edu-3autumn.localprod.forc.work/wp-login.php'
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'
}
data = {
    'log': input('请输入账号:'),
    'pwd': input('请输入密码:'),
    'wp-submit': '登录',
    'redirect_to': 'https://wordpress-edu-3autumn.localprod.forc.work/wp-admin/',
    'testcookie': '1'
}
session.post(url, headers=headers, data=data)
print(type(session.cookies))
# 打印cookies的类型,session.cookies就是登录的cookies
print(session.cookies)
# 打印cookies
复制代码

Save the cookies into code txt file

import requests
import json
# 引入requests和json模块。
session = requests.session()
url = ' https://wordpress-edu-3autumn.localprod.forc.work/wp-login.php'
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'
}
data = {
    'log': input('请输入你的账号:'),
    'pwd': input('请输入你的密码:'),
    'wp-submit': '登录',
    'redirect_to': 'https://wordpress-edu-3autumn.localprod.forc.work/wp-admin/',
    'testcookie': '1'
}
session.post(url, headers=headers, data=data)
cookies_dict = requests.utils.dict_from_cookiejar(session.cookies)
# 把cookies转化成字典。
print(cookies_dict)
# 打印cookies_dict
cookies_str = json.dumps(cookies_dict)
# 调用json模块的dumps函数,把cookies从字典再转成字符串。
print(cookies_str)
# 打印cookies_str
f = open('cookies.txt', 'w')
# 创建名为cookies.txt的文件,以写入模式写入内容。
f.write(cookies_str)
# 把已经转成字符串的cookies写入文件。
f.close()
# 关闭文件。
复制代码

Read cookies

String ==> Dictionary ==> cookies

cookies_txt = open('cookies.txt', 'r')
#以reader读取模式,打开名为cookies.txt的文件。
cookies_dict = json.loads(cookies_txt.read())
#调用json模块的loads函数,把字符串转成字典。
cookies = requests.utils.cookiejar_from_dict(cookies_dict)
#把转成字典的cookies再转成cookies本来的格式。
session.cookies = cookies
#获取cookies:就是调用requests对象(session)的cookies属性。
复制代码

The full version of the code

import requests
import json
session = requests.session()
# 创建会话。
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36'
}
# 添加请求头,避免被反爬虫。
try:
    # 如果能读取到cookies文件,执行以下代码,跳过except的代码,不用登录就能发表评论。
    cookies_txt = open('cookies.txt', 'r')
    # 以reader读取模式,打开名为cookies.txt的文件。
    cookies_dict = json.loads(cookies_txt.read())
    # 调用json模块的loads函数,把字符串转成字典。
    cookies = requests.utils.cookiejar_from_dict(cookies_dict)
    # 把转成字典的cookies再转成cookies本来的格式。
    session.cookies = cookies
    # 获取cookies:就是调用requests对象(session)的cookies属性。
except FileNotFoundError:
    # 如果读取不到cookies文件,程序报“FileNotFoundError”(找不到文件)的错,则执行以下代码,重新登录获取cookies,再评论。
    url = ' https://wordpress-edu-3autumn.localprod.forc.work/wp-login.php'
    # 登录的网址。
    data = {'log': input('请输入你的账号:'),
            'pwd': input('请输入你的密码:'),
            'wp-submit': '登录',
            'redirect_to': 'https://wordpress-edu-3autumn.localprod.forc.work/wp-admin/',
            'testcookie': '1'}
    # 登录的参数。
    session.post(url, headers=headers, data=data)
    # 在会话下,用post发起登录请求。
    cookies_dict = requests.utils.dict_from_cookiejar(session.cookies)
    # 把cookies转化成字典。
    cookies_str = json.dumps(cookies_dict)
    # 调用json模块的dump函数,把cookies从字典再转成字符串。
    f = open('cookies.txt', 'w')
    # 创建名为cookies.txt的文件,以写入模式写入内容
    f.write(cookies_str)
    # 把已经转成字符串的cookies写入文件
    f.close()
    # 关闭文件
url_1 = 'https://wordpress-edu-3autumn.localprod.forc.work/wp-comments-post.php'
# 文章的网址。
data_1 = {
    'comment': input('请输入你想评论的内容:'),
    'submit': '发表评论',
    'comment_post_ID': '13',
    'comment_parent': '0'
}
# 评论的参数。
comment = session.post(url_1, headers=headers, data=data_1)
# 在创建的session下用post发起评论请求,放入参数:文章网址,请求头和评论参数,并赋值给comment。
print(comment.status_code)
# 打印comment的状态码
复制代码

Analyzing plus cookies expired, a function package

import requests
import json
session = requests.session()
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36'
}
def cookies_read():
    '''
    cookies读取
    '''
    cookies_txt = open('cookies.txt', 'r')
    cookies_dict = json.loads(cookies_txt.read())
    cookies = requests.utils.cookiejar_from_dict(cookies_dict)
    return (cookies)
def save_cookies():
    '''
    cookies存储。
    '''
    url = ' https://wordpress-edu-3autumn.localprod.forc.work/wp-login.php'
    data = {
        'log': input('请输入你的账号'),
        'pwd': input('请输入你的密码'),
        'wp-submit': '登录',
        'redirect_to': 'https://wordpress-edu-3autumn.localprod.forc.work/wp-admin/',
        'testcookie': '1'
    }
    session.post(url, headers=headers, data=data)
    cookies_dict = requests.utils.dict_from_cookiejar(session.cookies)
    cookies_str = json.dumps(cookies_dict)
    f = open('cookies.txt', 'w')
    f.write(cookies_str)
    f.close()
    
def publish_comment():
    '''
    发表评论
    '''
    url_2 = 'https://wordpress-edu-3autumn.localprod.forc.work/wp-comments-post.php'
    data_2 = {
        'comment': input('请输入你要发表的评论:'),
        'submit': '发表评论',
        'comment_post_ID': '13',
        'comment_parent': '0'
    }
    return (session.post(url_2, headers=headers, data=data_2))
try:
    session.cookies = cookies_read()
except FileNotFoundError:
    save_cookies()
    session.cookies = cookies_read()
num = publish_comment()
# 判断cookies是否过期, 返回200说明没有过期
if num.status_code == 200:
    print('成功啦!')
else:
    save_cookies()
    session.cookies = cookies_read()
    num = publish_comment()
复制代码

Quick Jump:

Cat brother teach you to write reptile 000-- begins .md
cat brother teach you to write reptile 001 - print () functions and variables .md
cat brother teach you to write reptile 002-- job - Pikachu .md print
cat brother teach you to write reptiles 003 data type conversion .md
cat brother teach you to write reptile 004-- data type conversion - small practice .md
cat brother teach you to write reptile 005-- data type conversion - small jobs .md
cat brother teach you to write reptile 006- - conditional and nested conditions .md
cat brother teach you to write 007 reptile conditional and nested conditions - small operating .md
cat brother teach you to write reptile 008 - input () function .md
cat brother teach you to write reptiles 009 - input () function - AI little love students .md
cat brother teach you to write a list of 010 reptiles, dictionaries, circulation .md
cat brother teach you to write reptile 011-- lists, dictionaries, circulation - small jobs .md
cat brother teach you to write a Boolean value, and four reptile 012-- statements .md
cat brother teach you to write a Boolean value, and four reptile 013-- statements - smaller jobs .md
cat brother teach you to write reptile 014 - pk game. md
cat brother teach you to write reptile 015 - pk game (new revision) .md
cat brother teach you to write reptile 016-- function .md
cat brother teach you to write reptile 017-- function - a small job .md
cat brother to teach you write reptile 018--debug.md
cat brother teach you to write reptile 019 - debug- job. md
cat brother teach you to write reptiles 020-- Classes and Objects (on) .md
cat brother teach you to write reptiles 021-- Classes and Objects (a) - Job .md
Cat brother teach you to write reptiles 022-- Classes and Objects (lower) .md
cat brother teach you to write reptiles 023-- Classes and Objects (lower) - Job .md
cat brother teach you to write reptile 024-- decoding coded && .md
cat brother teach you to write reptile 025 && decoding coded - small jobs .md
cat brother teach you to write reptile 026-- module .md
cat brother teach you to write reptile 027-- module introduces .md
cat brother teach you to write reptile 028- - introduction module - small job - billboards .md
cat brother teach you to write Preliminary -requests.md reptile reptilian 029--
cat brother teach you to write reptile reptilian 030-- Preliminary -requests- job .md
cat brother teach you to write 031 reptiles - reptile basis -html.md
cat brother teach you to write reptile reptilian 032-- first experience -BeautifulSoup.md
cat brother teach you to write reptile reptilian 033-- first experience -BeautifulSoup- job .md
cat brother teach you to write reptile 034- - reptile -BeautifulSoup practice .md
cat brother teach you to write 035-- reptile reptilian -BeautifulSoup practice - job - film top250.md
cat brother teach you to write 036-- reptile reptilian -BeautifulSoup practice - work - work to resolve .md movie top250-
cat brother teach you to write 037-- reptile reptiles - to listen to songs .md baby
cat brother teach you to write reptile 038-- arguments request .md
cat brother teach you to write data stored reptile 039-- .md
cat brother teach you to write reptiles 040-- store data - Job .md
cat brother teach you to write reptile 041-- analog login -cookie.md
Cat brother teach you to write reptile 042 - session usage .md
cat brother teach you to write reptile 043-- analog browser .md
cat brother teach you to write reptile 044-- analog browser - job .md
cat brother teach you to write reptiles 045-- coroutine .md
cat brother teach you to write reptile 046-- coroutine - practice - what to eat not fat .md
cat brother teach you to write reptile 047 - scrapy framework .md
cat brother teach you to write reptile 048-- .md reptile reptiles and anti-
cat brother teach you to write reptile 049-- end Sahua .md

Reproduced in: https: //juejin.im/post/5cfc4add6fb9a07eae2a507d

Guess you like

Origin blog.csdn.net/weixin_34194087/article/details/91465278