我在為我的 graphql 解析器創建有效負載時遇到問題。如何重寫它以返回完成的數組?我被困在里面,無法返回數據。c.OnHTML("article", func(e *colly.HTMLElement) {}type Article struct { Title string `bson:"title"` Source string `bson:"source"` Url string `bson:"url"` Timestamp string `bson:"timestamp"`}func (r *RootResolver) News() ([]models.Article, error) { c := colly.NewCollector( colly.MaxDepth(2), colly.Async(), ) c.Limit(&colly.LimitRule{Parallelism: 10}) articles := []models.Article{} c.OnHTML("article", func(e *colly.HTMLElement) { articleModel := []models.Article{ { Title: e.ChildText("h3 a"), Source: e.ChildText("a[data-n-tid]"), Timestamp: e.ChildAttr("div:last-child time", "datetime"), Url: e.ChildAttr("a[href]", "href"), }, } fmt.Println(articleModel) }) c.Visit(SOMEURLHERE) c.Wait() return articles, nil}
1 回答

人到中年有點甜
TA貢獻1895條經驗 獲得超7個贊
如果需要獲取完整的文章列表,則需要將新文章追加到函數內部的切片中,而不是創建新切片。articles
c.OnHTML
并返回方法的切片末尾。articles
News()
articles = append(articles, models.Article{ Title: e.ChildText("h3 a"), Source: e.ChildText("a[data-n-tid]"), Timestamp: e.ChildAttr("div:last-child time", "datetime"), Url: e.ChildAttr("a[href]", "href"), })
在當前實現中, 創建類型的空片。在 內部,您創建了另一個名為 和 元素的類型切片。這兩個切片沒有任何聯系。因此,您需要將新元素附加到切片中,并將其與文章一起返回。articles := []models.Article{}
models.Article
c.OnHTML
models.Article
articleModel
articles
- 1 回答
- 0 關注
- 86 瀏覽
添加回答
舉報
0/150
提交
取消