854 views
Python开发

Python自动发布文章

文章目录

注意

在你的md文件开头 写入以下内容,value可以自定义,key与后面的脚本有关联,建议不要修改

---
title: Python自动发布文章
date: 2019-05-15 11:41:09
url: Python-auto-publish-markdown-post-to-WordPress
tag: 
    - "python"
category: "python开发"
----

安装需要的模块

pip3 install python-frontmatter
pip3 install markdown2
pip3 install python-xmlrpc-wordpress

创建一个fb.py文件

#!/usr/bin/env python3
#coding:utf8
#++++++++++++description++++++++++++#
"""
@author:ying
@contact:1074020480@qq.com
@site: 
@software: PyCharm
@file: fb.py
@time: 2019/5/15 上午10:36
"""
#+++++++++++++++++++++++++++++++++++#


import sys
import markdown2
import frontmatter
#获得md文章路径信息
dir = sys.argv[0]
#通过frontmatter.load函数加载读取文档里的信息
post = frontmatter.load(dir)
#将获取到的信息赋值给变量
post_title = post.metadata['title']
post_tag = post.metadata['tag']
post_category = post.metadata['category']
post_url = post.metadata['url']

#通过print函数来看我们获取到信息状态,确定无误后这个步骤是不需要的
print (post_title)
print (post_tag)
print (post_category)
print (post_url)
# print (post.content)
post_content_html=post.content

#同样导入发布文章需要的模块
from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.methods.posts import GetPosts,NewPost

wp = Client('http://你的域名/xmlrpc.php', '后台登录用户名', '后台登录密码')
#现在就很简单了,通过下面的函数,将刚才获取到数据赋给对应的位置
post = WordPressPost()
post.title = post_title
#post.slug文章别名
#我网站使用%postname%这种固定链接不想一长串,这里是最初md文章URL的参数,英文连字符格式
post.slug  = ''
post.content = post_content_html
#分类和标签
post.terms_names = {
  'post_tag': post_tag,
  'category': post_category
    }
post.post_status='publish' #有publish发布、draft草稿、private隐私状态可选,默认草稿。如果是publish会直接发布
# post.post_status = 'publish'
#推送文章到WordPress网站
wp.call(NewPost(post))
print('发布完成')

运行该文件

python3 fb.py /home/ying/Desktop/Python自动发布博客.md

wordpress_xmlrpc其他参数说明

python-wordpress-xmlrpc模块

官方文档:https://python-wordpress-xmlrpc.readthedocs.io/en/latest/ref/methods.html
wordpress需求:
1.修改某篇文章的 分类和标签  post_tag(分类目录),category(标签)
post.terms_names = {'post_tag': ['python高级技巧',],'category': ['python','Python开发']}
2.修改某篇文章的 名称tittle  post.title = '修改后的title'
3.修改某篇文章的 封面图      post.thumbnail = 图片id
4.修改某篇文章的 内容        post.content = '修改后的内容'

from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.methods import posts
from wordpress_xmlrpc.methods import.posts import GetPosts, NewPost,EditPost
from wordpress_xmlrpc.methods.users import GetUserInfo
<h1>建立连接与wordpress的链接</h1>
client = Client('http://你的网站域名/xmlrpc.php', '后台登录用户', '后台登录密码')
<h1>实例化post数据提交使用的类</h1>
post = WordPressPost()

post.thumbnail = 图片id
post.title = '修改后的title'
<h1>post_tag(标签),category(分类目录)</h1>
post.terms_names = {'post_tag': ['python高级技巧',],'category': ['python','Python开发']}

client.call(posts.NewPost(post)) #新增文章,所有数据都在post里面
client.call(posts.EditPost('文章id',post))#修改对应id的文章,所有数据都在post里面
client.call(posts.DeletePost('文章id',))#删除对应id的文章
影子专属博客 赣ICP备17013143号