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",
}
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()