python直接发布到网站wordpress之二发布图片

本文详细介绍了如何使用Python通过XML-RPC接口在WordPress上发布带有图片的文章,包括设置凭证、定义图片属性、读取文件并进行base64编码以及调用相关方法发送文章和图片。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在我的上一篇文章中已经给出了python操作wordpress的环境和发布文字的教程:

python直接发布到网站wordpress之一只发布文字-CSDN博客

本篇实现发布带图片的内容,无图无真相嘛。

直接上代码:

from wordpress_xmlrpc.methods.media import UploadFile
from wordpress_xmlrpc import Client
from wordpress_xmlrpc import WordPressPost
from wordpress_xmlrpc.methods.posts import NewPost

# Your credentials
url = 'http://你的域名.后缀名/xmlrpc.php'
username = '你的wordpress的账号名'
password = '你的wordpress的账号密码'

client = Client(url, username, password)

# Define your image and its properties
data = {
    'name': 'big_image.jpg',
    'type': 'image/jpeg',  # mimetype
}

# Read the binary file and let the XMLRPC library encode it into base64
with open('big_image.jpg', 'rb') as img:
    data['bits'] = img.read()

response = client.call(UploadFile(data))
attachment_id = response['id']

def send_post(title, content, attachment_id):
    post = WordPressPost()
    post.title = title
    post.content = content
    post.post_status = 'publish'
    post.thumbnail = attachment_id
    post_id = client.call(NewPost(post))

# Call the function
send_post("Your Title", "Your Content", attachment_id)

注:big_image.jpg是和代码.py同目录下的要发布的图片文件。 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值