如何将python采集到的文章保存到wordpress

727 阅读3分钟

小知识,大挑战!本文正在参与“  程序员必备小知识  ”创作活动

本文同时参与 「掘力星计划」  ,赢取创作大礼包,挑战创作激励金

第一种方法 直接操作数据库

第二种方法 使用wordpress的rest api

官方文档developer.wordpress.org/rest-api/

下面介绍第二种方法:

先试一下api的威力 格式为:

http://{域名}/index.php/wp-json/wp/v2/posts

比如:

www.jhcms.net/index.php/w…

如何创建一个新文章

官方文档 developer.wordpress.org/rest-api/re…

得到重要信息如下:

参数

dateThe date the object was published, in the site’s timezone.
date_gmtThe date the object was published, as GMT.
slugAn alphanumeric identifier for the object unique to its type.
statusA named status for the object. One of: publish, future, draft, pending, private
passwordA password to protect access to the content and excerpt.
titleThe title for the object.
contentThe content for the object.
authorThe ID for the author of the object.
excerptThe excerpt for the object.
featured_mediaThe ID of the featured media for the object.
comment_statusWhether or not comments are open on the object. One of: open, closed
ping_statusWhether or not the object can be pinged. One of: open, closed
formatThe format for the object. One of: standard, aside, chat, gallery, link, image, quote, status, video, audio
metaMeta fields.
stickyWhether or not the object should be treated as sticky.
templateThe theme file to use to display the object. One of:``
categoriesThe terms assigned to the object in the category taxonomy.
tagsThe terms assigned to the object in the post_tag taxonomy.

定义#Definition

POST /wp/v2/posts 意为要用post方法提交到 /wp/v2/posts这个地址

默认是只读api要实现提交数据需要安装插件jwt,安装了jwt后可以请求到token了,在rest api中传入token信息,系统就不会拒绝你的发布文章的操作了

操作步骤

  1. 第一步 在wordpress管理后台安装 JWT Auth 插件

  2. 第二部 在网站根目录 .htaccess 文件中添加如下内容

    RewriteEngine on
    RewriteCond %{HTTP:Authorization} ^(.*)
    RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]
    
    SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
    
  3. wp-config.php 文件中添加如下内容:

    define('JWT_AUTH_SECRET_KEY', 'your-top-secret-key');//随便填写一个密码
    define('JWT_AUTH_CORS_ENABLE', true);
    
  4. Post请求调用http://{你的域名}/wp-json/jwt-auth/v1/token接口获取token

  5. 根据token进行文章的发布

核心代码如下:

# -*- coding:utf-8 -*-

import re
import requests
import json
import time
from numpy import *




def get_token():
    session = requests.Session()
    url = 'http://sex.newban.cn/wp-json/jwt-auth/v1/token'
    data = {
        'username':"son3g",
        'password':"123456"
        }
    headers = {'user-agent': 'Mozolla/5.0',
               }
    resp = session.post(url, data=data, headers=headers, timeout=3335)  # 请求
    r = json.loads(resp.content)
    return r




def _do_post( token =''):
        session = requests.Session()
        url = 'http://sex.newban.cn/wp-json/wp/v2/posts'
        data = {
                'date': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()),
                'date_gmt': time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime()),
                'slug': 'xx',
                'status': 'publish',
                'password': '',
                'title': 'rest api发布post测试',
                'content': '系统测试我想我是海冬天的大海',
                'author	': '121852835@qq.com',
                'excerpt': '',
                'featured_media': '0',
                'comment_status': 'open',
                'ping_status': 'closed',
                'format': 'standard',
                'meta': [],
                'sticky': False,  # 置顶
                'template': '',
                'categories': '1',  # 1 未分类
                'tags': ''
        }
        headers = {'user-agent': 'Mozolla/5.0',
                   'Authorization': 'Bearer ' + token
                   }
        resp = session.post(url, data=data, headers=headers, timeout=3335)  # 请求
        print (resp.text)
        # r = json.loads(resp.content, 'utf-8')

        # if r["code"] == 400:
        #         print r["code"]
        #         print r["message"]
        #         print r["data"]
        #         print r["data"]["status"]
        #
        #
        #         # print r["data"]["params"]
        #         for key in r["data"]["params"]:
        #             print ("%s=> %s" % (key, r["data"]["params"][key]))
        #         # print 'resp.text=>' + resp.text
        #
        #         # print time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
        #         # print time.strftime('%a, %d %b %Y %H:%M:%S GMT+0800 (CST)',time.localtime(time.time())),
        #         dt = formatdate(None, usegmt=True)
        #         dt1 = formatdate(None, usegmt=False)
        #         dt3 = formatdate()
        #         print(dt)
        #         print(dt1)
        # else:
        #         print r["code"]
        #         print r["message"]
        #         print resp.status_code


if __name__=='__main__':
        r = get_token()
        print (r)
        _do_post(r["data"]['token'])

「欢迎在评论区讨论,掘金官方将在掘力星计划活动结束后,在评论区抽送100份掘金周边,抽奖详情见活动文章」