带上传文件功能的写CSDN博客并发表

该篇在前面的基础上增加了上次文件的功能,并对代码做了简单的封装,贴上代码,上面有比较详细的注释:

apiMethod.py文件:

# coding:utf-8
import requests
from bs4 import BeautifulSoup
class ApiMethod():
    def __init__(self,userAgent):
        self.h = {"User-Agent": userAgent}
    #通过session来登录CSDN,保持一直登录状态
    def loginCsdn(self):
        try:
            s= requests.session()
            c = requests.cookies.RequestsCookieJar()
            c.set("UserInfo","ltxlmnyec9obNIiCirM0KBmlYeijHfUcQ%2BZE7J%2B%2Ffk1djT8xd36OsnAqrYJ46KvVN8f%2BdG6KiVfFSHuxAmSJTT8VFZF%2FpmyBVj3McsPss%2FAH6gR3SuyN3ms9A9pd7xaq8T%2FZ%2Fcr5ZOVFqSGjNvpRqQ%3D%3D")
            c.set("UserNick","%E9%A3%8E%E6%A5%9A%E9%A2%9C")
            c.set("AU","FCF")
            c.set("Hm_lpvt_6bcd52f51e9b3dce32bec4a3997715ac","1521982541")
            c.set("dc_tos","p65d8s")
            c.set("UserName","maybe_frank")
            s.cookies.update(c)
            re = s.get("https://mp.csdn.net/postedit",headers = self.h)
            soup = BeautifulSoup(re.content,"html.parser")
            title = soup.title.string
            if title == "写文章-CSDN博客":
                print("登录成功!")
            else:
                print("登录失败")
            return s
        except Exception as e:
            print(e)

    def upload(self,session,urlPath,fileName,file):
        try:
            f = {"file":(fileName,open(file,"rb"),"image/png")}
            re = session.post(url=urlPath,headers = self.h,files = f)
            return re.json()["content"]
        except Exception as e:
            print(e)

    def write(self,session,urlPath,data):
        try:
            body = data
            re = session.post(url=urlPath,headers = self.h,data=body)
            #返回上传图片后的图片url
            return  re.json()["content"]
        except Exception as e:
            print(e)


if __name__ == '__main__':
    sf = ApiMethod("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:58.0) Gecko/20100101 Firefox/58.0")
    s = sf.loginCsdn()
    sf.upload(s,"https://mp.csdn.net/UploadImage","Q1.png","C:\\Users\\ztf.YFK\\Desktop\\1.png")
    data = {"titl":"wers",
             "typ":1,
             "cont":'

上传文件:


', "categories":"接口", "chnl":16, "level":0, "tag2":"", "artid":0, "private":"false", "stat":"publish"} content = sf.write(s,"https://mp.csdn.net/postedit/saveArticle?isPub=1",data) print(content)

调用入口:writeBlog.py

from csdn.apiMethod import ApiMethod
import unittest
import time
import random
class WriteBlog(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.sf = ApiMethod("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:58.0) Gecko/20100101 Firefox/58.0")
        cls.s = cls.sf.loginCsdn()

    @classmethod
    def tearDownClass(cls):
        pass

    def test_writeBlog(self):
        file_url = self.upload(self.s,"https://mp.csdn.net/UploadImage","Q1.png","C:\\Users\\ztf.YFK\\Desktop\\1.png")
        print("上传文件后的url:",end="")
        print(file_url)
        #发布博客时的传的body的数据
        num= random.randint(1,1000)
        self.data = {"titl":"wers%s"%num,
         "typ":1,
         "cont":'

上传文件:


', "categories":"接口", "chnl":16, "level":0, "tag2":"", "artid":0, "private":"false", "stat":"publish"} #调用发布博客接口 content = self.sf.write(self.s,"https://mp.csdn.net/postedit/saveArticle?isPub=1",self.data) print(content) #self.assertTrue(self,content,"发布成功!") self.assertEqual(self,content,"发布成功","调用发布博客接口请求失败!") if __name__ == '__main__': unittest.main()


你可能感兴趣的:(接口)