编辑代码

# coding:utf-8
#JSRUN引擎2.0,支持多达30种语言在线运行,全仿真在线交互输入输出。 
print("Hello world!   -  python.jsrun.net .")import requests
import json

# 小红书搜索接口(示例,实际接口可能不同)
SEARCH_URL = "https://www.xiaohongshu.com/api/search"
# 小红书留言接口(示例,实际接口可能不同)
COMMENT_URL = "https://www.xiaohongshu.com/api/comment"

# 请求头(模拟浏览器请求)
HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
    "Referer": "https://www.xiaohongshu.com/",
    "Content-Type": "application/json",
}

# 登录后的 Cookie(需要手动获取)
COOKIES = {
    "your_cookie_key": "your_cookie_value"
}

def search_xiaohongshu(keyword):
    """按关键字搜索小红书内容"""
    params = {
        "keyword": keyword,
        "page": 1,
        "page_size": 10
    }
    response = requests.get(SEARCH_URL, headers=HEADERS, params=params, cookies=COOKIES)
    if response.status_code == 200:
        data = response.json()
        return data.get("data", {}).get("notes", [])
    else:
        print(f"搜索失败,状态码:{response.status_code}")
        return []

def post_comment(note_id, content):
    """在指定笔记下留言"""
    payload = {
        "note_id": note_id,
        "content": content
    }
    response = requests.post(COMMENT_URL, headers=HEADERS, cookies=COOKIES, json=payload)
    if response.status_code == 200:
        print(f"留言成功:{content}")
    else:
        print(f"留言失败,状态码:{response.status_code}")

def main():
    # 搜索关键字
    keyword = "Python"
    notes = search_xiaohongshu(keyword)
    if not notes:
        print("未找到相关内容")
        return

    # 打印搜索结果
    print(f"找到 {len(notes)} 条相关内容:")
    for note in notes:
        print(f"笔记ID: {note['id']}, 标题: {note['title']}")

    # 选择第一条笔记留言
    note_id = notes[0]["id"]
    comment_content = "这是一个测试留言,感谢分享!"
    post_comment(note_id, comment_content)

if __name__ == "__main__":
    main()