下载地址:https://www.pan38.com/dow/share.php?code=JCnzE 提取密码:1133
Pillow库自动生成符合平台尺寸要求的配图7;3)利用Playwright实现自动化发布流程6。代码采用面向对象设计,可通过继承XHSGenerator类扩展更多模板类型19。
主要技术特点:
文案生成支持emoji和话题标签自动插入
图片生成采用1080x1350的标准小红书竖图比例
发布模块模拟人工操作流程,降低被封风险
支持多张图片批量上传
import requests
import json
from PIL import Image, ImageDraw, ImageFont
import random
import os
from playwright.sync_api import sync_playwright
class XHSGenerator:
def init(self):
self.api_key = "your_baidu_api_key"
self.secret_key = "your_baidu_secret_key"
self.templates = {
"food": "美食探店模板",
"beauty": "美妆种草模板",
"travel": "旅行攻略模板"
}
def get_access_token(self):
"""获取百度文心API访问令牌"""
url = "https://aip.baidubce.com/oauth/2.0/token"
params = {
"grant_type": "client_credentials",
"client_id": self.api_key,
"client_secret": self.secret_key
}
response = requests.post(url, params=params)
return response.json().get("access_token")
def generate_content(self, prompt):
"""使用文心一言生成小红书文案"""
access_token = self.get_access_token()
if not access_token:
return None
url = f"https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token={access_token}"
payload = {
"messages": [{
"role": "user",
"content": f"作为小红书博主,请生成一篇关于{prompt}的文案,包含3个emoji和2个话题标签,语言风格活泼"
}],
"temperature": 0.7,
"max_tokens": 500
}
response = requests.post(url, json=payload)
return response.json().get("result")
def create_image(self, text, output_path):
"""生成小红书风格配图"""
width, height = 1080, 1350 # 小红书竖图比例
bg_color = (255, 255, 255)
image = Image.new("RGB", (width, height), bg_color)
draw = ImageDraw.Draw(image)
try:
font = ImageFont.truetype("arial.ttf", 40)
except:
font = ImageFont.load_default()
text_width, text_height = draw.textsize(text, font=font)
position = ((width - text_width) // 2, (height - text_height) // 2)
draw.text(position, text, fill=(0, 0, 0), font=font)
# 添加装饰元素
for _ in range(5):
x = random.randint(0, width)
y = random.randint(0, height)
r = random.randint(5, 20)
draw.ellipse([x-r, y-r, x+r, y+r], fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
image.save(output_path)
return output_path
def auto_post(self, content, image_paths):
"""使用Playwright自动发布到小红书"""
with sync_playwright() as p:
browser = p.chromium.launch(headless=False)
context = browser.new_context()
page = context.new_page()
# 登录流程(需提前登录)
page.goto("https://creator.xiaohongshu.com")
page.wait_for_selector("#title")
# 填写内容
page.fill("#title", content[:20]) # 标题取前20字
page.fill("#content", content)
# 上传图片
for i, img_path in enumerate(image_paths):
page.click(f".upload-btn-{i+1}")
page.set_input_files(f"input[type=file]", img_path)
# 发布
page.click("#submit-btn")
page.wait_for_timeout(5000)
browser.close()
if name == "main":
generator = XHSGenerator()
topic = input("请输入内容主题: ")
# 生成文案
content = generator.generate_content(topic)
print("生成的文案:\n", content)
# 生成配图
image_paths = []
for i in range(3): # 生成3张配图
img_path = f"output_{i}.jpg"
generator.create_image(f"{topic} - 图{i+1}", img_path)
image_paths.append(img_path)
# 自动发布(需配置账号)
# generator.auto_post(content, image_paths)
print("图文生成完成,已保存到本地")