Python中如何实现自动发布文章到WordPress

作为一个 python 萌新,需要使用 python 自动发布文章,需求如下:
1.文章内容为纯图片形式,每篇文章所需图片均在不同文件夹下
2.文章标题使用图片文件夹名称
3.不要找我索取 VIP 谢谢

特来请教各位有没有什么比较好的思路,或者操作方式


Python中如何实现自动发布文章到WordPress
3 回复

帖子回复:

要在Python中自动发布文章到WordPress,最直接的方法是使用WordPress的REST API。你需要先获取API凭证,然后通过requests库发送HTTP请求。下面是一个完整的示例:

import requests
from requests.auth import HTTPBasicAuth
import json

# WordPress站点信息
WORDPRESS_URL = "https://your-site.com/wp-json/wp/v2"
USERNAME = "your_username"
PASSWORD = "your_password"  # 或使用应用密码

# 文章数据
post_data = {
    'title': '我的测试文章',
    'content': '这是通过Python自动发布的内容。',
    'status': 'publish',  # 草稿用'draft'
    'categories': [1],    # 分类ID
    'tags': [5, 10]       # 标签ID列表
}

# 发送POST请求创建文章
response = requests.post(
    f"{WORDPRESS_URL}/posts",
    auth=HTTPBasicAuth(USERNAME, PASSWORD),
    json=post_data,
    headers={'Content-Type': 'application/json'}
)

# 检查响应
if response.status_code == 201:
    print("文章发布成功!")
    print(f"文章ID: {response.json()['id']}")
    print(f"文章链接: {response.json()['link']}")
else:
    print(f"发布失败,状态码: {response.status_code}")
    print(f"错误信息: {response.text}")

关键点说明:

  1. API凭证:在WordPress后台“用户”->“个人资料”中生成“应用密码”,或使用插件创建API密钥。
  2. 文章状态status字段设为'publish'直接发布,设为'draft'则保存为草稿。
  3. 分类和标签:需要提前在WordPress中创建并获取其ID,可通过GET请求/categories/tags端点查看。
  4. 媒体上传:如需上传图片,先POST到/media端点获取附件ID,再在文章内容中引用。

替代方案: 如果觉得直接操作API麻烦,可以用第三方库python-wordpress-xmlrpc(基于旧版XML-RPC接口),但REST API更现代且功能更全。

总结建议: 用REST API配合requests库是最灵活可靠的方法。


获取发送文章的 API 然后 python 模拟就行了

from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.compat import xmlrpc_client
from wordpress_xmlrpc.methods import media
from wordpress_xmlrpc.methods.posts import GetPosts,NewPost

自己去研究,自己写呀。

回到顶部