菜鸟笔记
提升您的技术认知

wordpress批量发布内容python脚本

# !/usr/bin python3                                 
# encoding    : utf-8 -*-                            
# @author     :   coonote                               
# @software   : PyCharm      
# @file       :   wordpress.py
# @Time       :   2021/1/8 10:19 下午

from threading import Thread
from queue import Queue
from pymongo import MongoClient,collection
import requests
import time

class Wordpress_Post(Thread):
    def __init__(self, queue, config):
        super(Wordpress_Post,self).__init__()
        self.queue = queue
        self.config = config

    def run(self) -> None:
        while True:
            try:
                title, content = self.queue.get()
                form = self.make_form(title, content)
                rts = self.post_article(form)
                print(f'{title} {rts}')
            finally:
                self.queue.task_done()

    def post_article(self, form):
        try:
            r = requests.post(self.config['api'], data=form, timeout=10)
        except requests.Timeout:
            return self.post_article(form)
        r.encoding = 'utf-8'
        print(r.text)

    def make_form(self, title, content):
        return {
            'post_title':title, # 标题
            'post_content':content, # 内容
            'tag':'', # 标签
            'post_category':'', # 分类
            'post_data':'', # 时间
            'post_excerpt':'', # 摘要
            'post_author':'junge',  # 作者
            'category_description':'', # 分类信息
            'post_cate_meta[name]':'', # 自定义分类信息
            'post_meta[name]':'', # 自定义字段
            'post_type':'post', # 文章类型 默认为'post'
            'post_taxonomy':'', # 自定义分类方式
            'post_format':'', # 文章形式
        }

# read_article_from_db函数遍历读取mongodb里面数据title,content
def read_article_from_db(collect: collection.Collection, from_, num, queue: Queue):
    # 查找全部数据title,content
    result = collect.find({}, {'_id': 0, 'title': 1, 'content': 1}, skip=from_, limit=num)
    # 遍历出result里面的数据
    for item in result:
        # put到消息列队里面
        queue.put((item['title'], item['content']))


if __name__ == '__main__':
    article_queue = Queue(100)
    client = MongoClient()
    db = client['shuju']
    table = db['article']
    rdb = Thread(target=read_article_from_db, args=(table, 1000, 100, article_queue))
    # 守护线程True
    rdb.daemon = True
    # 启动线程
    rdb.start()
    # 延时一秒
    time.sleep(1)
    post_config = {
        'api':'这里写接口地址',
        'id':1
     }
    api = '这里写接口地址'
    for _ in range(10):
        wp = Wordpress_Post(article_queue,post_config)
        wp.daemon = True
        wp.start()

    article_queue.join()
    print('发布完成')