feat: 添加搜索功能 (#16)
- 新增 SearchFeeds 服务方法,支持关键词搜索小红书内容 - 添加 search_feeds MCP 工具,提供搜索接口 - 新增 /api/v1/feeds/search API 端点 - 实现搜索页面的浏览器自动化操作 - 优化 MCP 协议支持,处理 notifications/initialized 和 notifications/cancelled 通知 - 更新文档,添加搜索功能说明和使用示例 - 重构类型定义,优化数据结构 🤖 Generated with [Claude Code](https://claude.ai/code) Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
65
xiaohongshu/search.go
Normal file
65
xiaohongshu/search.go
Normal file
@@ -0,0 +1,65 @@
|
||||
package xiaohongshu
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/go-rod/rod"
|
||||
)
|
||||
|
||||
type SearchResult struct {
|
||||
Search struct {
|
||||
Feeds FeedsValue `json:"feeds"`
|
||||
} `json:"search"`
|
||||
}
|
||||
|
||||
type SearchAction struct {
|
||||
page *rod.Page
|
||||
}
|
||||
|
||||
func NewSearchAction(page *rod.Page) *SearchAction {
|
||||
pp := page.Timeout(60 * time.Second)
|
||||
|
||||
return &SearchAction{page: pp}
|
||||
}
|
||||
|
||||
func (s *SearchAction) Search(ctx context.Context, keyword string) ([]Feed, error) {
|
||||
page := s.page.Context(ctx)
|
||||
|
||||
searchURL := makeSearchURL(keyword)
|
||||
page.MustNavigate(searchURL)
|
||||
page.MustWaitStable()
|
||||
|
||||
page.MustWait(`() => window.__INITIAL_STATE__ !== undefined`)
|
||||
|
||||
// 获取 window.__INITIAL_STATE__ 并转换为 JSON 字符串
|
||||
result := page.MustEval(`() => {
|
||||
if (window.__INITIAL_STATE__) {
|
||||
return JSON.stringify(window.__INITIAL_STATE__);
|
||||
}
|
||||
return "";
|
||||
}`).String()
|
||||
|
||||
if result == "" {
|
||||
return nil, fmt.Errorf("__INITIAL_STATE__ not found")
|
||||
}
|
||||
|
||||
var searchResult SearchResult
|
||||
if err := json.Unmarshal([]byte(result), &searchResult); err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal __INITIAL_STATE__: %w", err)
|
||||
}
|
||||
|
||||
return searchResult.Search.Feeds.Value, nil
|
||||
}
|
||||
|
||||
func makeSearchURL(keyword string) string {
|
||||
|
||||
values := url.Values{}
|
||||
values.Set("keyword", keyword)
|
||||
values.Set("source", "web_explore_feed")
|
||||
|
||||
return fmt.Sprintf("https://www.xiaohongshu.com/search_result?%s", values.Encode())
|
||||
}
|
||||
Reference in New Issue
Block a user