我有一个结构如下:
Type Post struct{
ID int64
Title string
Content string
}
我用Go Colly curl 网页以接收数据,我有两个OnHtml方法,如下所示:
func main() {
c := colly.NewCollector()
c.OnHTML("p", func(e *colly.HTMLElement) {
Post := Post{
Content: e.Text
}
db.Create(&Post)
})
c.OnHTML("h", func(e *colly.HTMLElement) {
Post := Post{
Title: e.Text
}
db.Create(&Post)
})
c.Visit("http://go-colly.org/")
}
上面的代码运行良好,但是会在数据库中创建两行,如下所示:
+--------------+---------------+---------------+
| id | title | content |
+--------------+---------------+---------------+
| 1 | Hello | Null |
+--------------+---------------+---------------+
| 2 | Null | Mycontent ... |
+--------------+---------------+---------------+
我想创建它:
+--------------+---------------+---------------+
| id | title | content |
+--------------+---------------+---------------+
| 1 | Hello | Mycontent ... |
+--------------+---------------+---------------+
如何获取两个元素并保存到goly中的一行中?
最佳答案
您应该阅读以下示例:http://go-colly.org/docs/examples/coursera_courses/在存在detailCollector.OnHTML("div[id=rendered-content]", func(e *colly.HTMLElement) {
的行
该示例在封装整个内容的元素(此处为div)上设置onHTML,因此对于您来说,您需要找到封装包含标题和内容的每个帖子的元素,然后执行e.ForEach来解析每个帖子。
编辑:http://go-colly.org/docs/examples/factbase/还是您的用例的一个很好的例子。捕获 body ,然后用演讲者和文字分析每个主题。
明白了吗?
关于go - 如何使用go colly在页面上获取多个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60596820/