接口登录CSDN发布博客---封装方法,使用unittest框架

一个简单的跑接口流程:登录后发表带图片的博客。这里涉及到的知识点:

1、登录时通过cookies去保持登录状态,把cookies添加到一个session中,这样可以保持长时间登录状态;

2、我们通过爬虫获取页面的title标签的文本判断登录成功;

3、通过抓包找到上传图片的地址,通过post方式来上传图片;

4、抓包找到发布博客的地址,最后发布博客;

5、使用了unittest框架来完成接口流程测试,作为一个测试用例。

 

ApiMethod.py的代码如下:

 1 # coding:utf-8
 2 import requests
 3 from bs4 import BeautifulSoup
 4 class ApiMethod():
 5     def __init__(self,userAgent):
 6         self.h = {"User-Agent": userAgent}
 7     #通过session来登录CSDN,保持一直登录状态
 8     def loginCsdn(self):
 9         try:
10             s= requests.session()
11             c = requests.cookies.RequestsCookieJar()
12             c.set("UserInfo","ltxlmnyec9obNIiCirM0KBmlYeijHfUcQ%2BZE7J%2B%2Ffk1djT8xd36OsnAqrYJ46KvVN8f%2BdG6KiVfFSHuxAmSJTT8VFZF%2FpmyBVj3McsPss%2FAH6gR3SuyN3ms9A9pd7xaq8T%2FZ%2Fcr5ZOVFqSGjNvpRqQ%3D%3D")
13             c.set("UserNick","%E9%A3%8E%E6%A5%9A%E9%A2%9C")
14             c.set("AU","FCF")
15             c.set("Hm_lpvt_6bcd52f51e9b3dce32bec4a3997715ac","1521982541")
16             c.set("dc_tos","p65d8s")
17             c.set("UserName","maybe_frank")
18             s.cookies.update(c)
19             re = s.get("https://mp.csdn.net/postedit",headers = self.h)
20             soup = BeautifulSoup(re.content,"html.parser")
21             title = soup.title.string
22             if title == "写文章-CSDN博客":
23                 print("登录成功!")
24             else:
25                 print("登录失败")
26             return s
27         except Exception as e:
28             print(e)
29 
30     def upload(self,session,urlPath,fileName,file):
31         try:
32             f = {"file":(fileName,open(file,"rb"),"image/png")}
33             re = session.post(url=urlPath,headers = self.h,files = f)
34             return re.json()["content"]
35         except Exception as e:
36             print(e)
37 
38     def write(self,session,urlPath,data):
39         try:
40             body = data
41             re = session.post(url=urlPath,headers = self.h,data=body)
42             #返回上传图片后的图片url
43             return  re.json()["content"]
44         except Exception as e:
45             print(e)
46 
47 
48 if __name__ == '__main__':
49     sf = ApiMethod("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:58.0) Gecko/20100101 Firefox/58.0")
50     s = sf.loginCsdn()
51     sf.upload(s,"https://mp.csdn.net/UploadImage","Q1.png","C:\\Users\\ztf.YFK\\Desktop\\1.png")
52     data = {"titl":"wers",
53              "typ":1,
54              "cont":'<p>上传文件:</p><p><img src="https://img-blog.csdn.net/20180326110705916" alt="" /><br /></p>',
55              "categories":"接口",
56              "chnl":16,
57              "level":0,
58              "tag2":"",
59              "artid":0,
60              "private":"false",
61              "stat":"publish"}
62     content = sf.write(s,"https://mp.csdn.net/postedit/saveArticle?isPub=1",data)
63     print(content)

 

write.py的代码如下:

 1 from csdn.apiMethod import ApiMethod
 2 import unittest
 3 import time
 4 import random
 5 class WriteBlog(unittest.TestCase):
 6     @classmethod
 7     def setUpClass(cls):
 8         cls.sf = ApiMethod("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:58.0) Gecko/20100101 Firefox/58.0")
 9         cls.s = cls.sf.loginCsdn()
10 
11     @classmethod
12     def tearDownClass(cls):
13         pass
14 
15     def test_writeBlog(self):
16         file_url = self.upload(self.s,"https://mp.csdn.net/UploadImage","Q1.png","C:\\Users\\ztf.YFK\\Desktop\\1.png")
17         print("上传文件后的url:",end="")
18         print(file_url)
19         #发布博客时的传的body的数据
20         num= random.randint(1,1000)
21         self.data = {"titl":"wers%s"%num,
22          "typ":1,
23          "cont":'<p>上传文件:</p><p><img src="https://img-blog.csdn.net/20180326110705916" alt="" /><br /></p>',
24          "categories":"接口",
25          "chnl":16,
26          "level":0,
27          "tag2":"",
28          "artid":0,
29          "private":"false",
30          "stat":"publish"}
31 
32         #调用发布博客接口
33         content = self.sf.write(self.s,"https://mp.csdn.net/postedit/saveArticle?isPub=1",self.data)
34         print(content)
35         #self.assertTrue(self,content,"发布成功!")
36         self.assertEqual(self,content,"发布成功","调用发布博客接口请求失败!")
37 
38     if __name__ == '__main__':
39         unittest.main()

运行后,可以去CSDN博客查看是否发布成功。代码经实际调试可以跑成功。

 

posted @ 2018-03-26 15:22  风楚颜  阅读(1108)  评论(0编辑  收藏  举报