python接口自動化3-自動發帖(session)
前言
上一篇模擬登錄博客園,但這只是第一步,一般登錄後,還會有其它的操作,如發帖,評論等,這時候如何保持會話呢?
一、session簡介
1.查看幫助文檔,貼了一部分,後面省略了
>>import requests
>>help(requests.session())
class Session(SessionRedirectMixin)
| A Requests session.
|
| Provides cookie persistence, connection-pooling, and configuration.
|
| Basic Usage::
| >>> import requests
| >>> s = requests.Session()
| >>> s.get(‘http://httpbin.org/get‘)
| <Response [200]>
|
| Or as a context manager::
|
| >>> with requests.Session() as s:
| >>> s.get(‘http://httpbin.org/get‘)
| <Response [200]>
二、使用session登錄
1.使用session登錄只需在上一篇基礎上稍做修改
# coding:utf-8
import requests
url = "https://passport.cnblogs.com/user/signin"
headers = {
頭部信息已省略
}
payload = {"input1":"xxx",
"input2":"xxx",
"remember":True}
# r = requests.post(url, json=payload, headers=headers,verify=False)
# 修改後如下
s = requests.session()
r = s.post(url, json=payload, headers=headers,verify=False)
print r.json()
三、保存編輯
1.先打開我的隨筆,手動輸入內容後,打開fiddler抓包
2.把body的參數內容寫成字典格式,有幾個空的參數不是必填的,可以去掉
body = {"__VIEWSTATE": "",
"__VIEWSTATEGENERATOR":"FE27D343",
"Editor$Edit$txbTitle":"這是我的標題:上海-悠悠",
"Editor$Edit$EditorBody":"<p>這裏是中文內容:http://www.cnblogs.com/yoyoketang/</p>",
"Editor$Edit$Advanced$ckbPublished":"on",
"Editor$Edit$Advanced$chkDisplayHomePage":"on",
"Editor$Edit$Advanced$chkComments":"on",
"Editor$Edit$Advanced$chkMainSyndication":"on",
"Editor$Edit$lkbDraft":"存為草稿",
}
3.用上面的session繼續發送post請求
4.執行後,查看我的草稿箱就多了一條新增的了
四、參考代碼
# coding:utf-8
import requests
url = "https://passport.cnblogs.com/user/signin"
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0",
"Accept": "application/json, text/javascript, */*; q=0.01",
"Accept-Language": "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3",
"Accept-Encoding": "gzip, deflate, br",
"Content-Type": "application/json; charset=utf-8",
# "VerificationToken": "xxx...", # 已省略
"X-Requested-With": "XMLHttpRequest",
# "Referer": "https://passport.cnblogs.com/user/signin?ReturnUrl=http%3a%2f%2fmsg.cnblogs.com%2fsend%2f%e4%b8%8a%e6%b5%b7-%e6%82%a0%e6%82%a0",
"Content-Length": "385",
"Cookie": "xxx.....", # 已省略
"Connection": "keep-alive"
}
# 登錄的參數
payload = {"input1":"xxx",
"input2":"xxx",
"remember":True}
s = requests.session()
r = s.post(url, json=payload, headers=headers,verify=False)
print r.json()
# 保存草稿箱
url2= "https://i.cnblogs.com/EditPosts.aspx?opt=1"
body = {"__VIEWSTATE": "",
"__VIEWSTATEGENERATOR":"FE27D343",
"Editor$Edit$txbTitle":"這是我的標題:上海-悠悠",
"Editor$Edit$EditorBody":"<p>這裏是中文內容:http://www.cnblogs.com/yoyoketang/</p>",
"Editor$Edit$Advanced$ckbPublished":"on",
"Editor$Edit$Advanced$chkDisplayHomePage":"on",
"Editor$Edit$Advanced$chkComments":"on",
"Editor$Edit$Advanced$chkMainSyndication":"on",
"Editor$Edit$lkbDraft":"存為草稿",
}
r2 = s.post(url2, data=body, verify=False)
print r.content
這裏我是用保存草稿箱寫的案例,小夥伴們可以試下自動發帖
(備註:別使用太頻繁了哦,小心封號嘿嘿!!!)
對python接口自動化有興趣的,可以加python接口自動化QQ群:226296743
也可以關註下我的個人公眾號:
python接口自動化3-自動發帖(session)