gpt4 book ai didi

golang web scraper,忽略表格的特定单元格

转载 作者:IT王子 更新时间:2023-10-29 01:02:50 26 4
gpt4 key购买 nike

我正在开发一个小型网络抓取工具来感受一下 golang。它目前正在从表格中获取 wiki 的信息,然后专门从单元格中获取信息。我目前没有密码(目前不在家),但它看起来与此非常相似:

    func main() {
doc, err := goquery.NewDocument("http://monsterhunter.wikia.com/wiki/MH4:_Item_List")
if err != nil {
log.Fatal(err)
}

doc.Find("tbody").Each(func(i int, s *goquery.Selection) {
title := s.Find("td").Text()
fmt.Printf(title)
})
}

问题是在这个网站上,第一个单元格是一个图像,所以它打印了我不想要的图像源。如何忽略大表格每一行的第一个单元格?

最佳答案

让我们清除一些东西。 Selection是符合某些条件的节点的集合。

doc.Find()Selection.Find()它返回一个新的 Selection,其中包含符合条件的元素。和 Selection.Each()迭代集合中的每个元素并调用传递给它的函数值。

因此在您的情况下,Find("tbody") 将找到所有 tbody 元素,Each() 将遍历所有 tbody 元素并调用您的匿名函数。

在您的匿名函数 s 中是一个 tbody 元素的 Selection。您调用 s.Find("td") 将返回一个新的 Selection,其中将包含 all td当前表的元素。所以当你调用Text()在这一点上,它将是每个 td 元素(包括它们的后代)的组合文本内容。这不是您想要的。

您应该做的是在 s.Find("td") 返回的 Selection 上调用另一个 Each()。并检查传递给第二个匿名函数的 Selection 是否有一个 img child 。

示例代码:

doc.Find("tbody").Each(func(i int, s *goquery.Selection) {
// s here is a tbody element
s.Find("td").Each(func(j int, s2 *goquery.Selection) {
// s2 here is a td element
if s3 := s2.Find("img"); s3 != nil && s3.Length() > 0 {
return // This TD has at least one img child, skip it
}
fmt.Printf(s2.Text())
})
})

或者,您可以搜索 tr 元素并跳过每行的第一个 td 子元素,方法是检查传递给第三个匿名函数的索引是否为 0(第一个 child ),像这样:

doc.Find("tbody").Each(func(i int, s *goquery.Selection) {
// s here is a tbody element
s.Find("tr").Each(func(j int, s2 *goquery.Selection) {
// s2 here is a tr element
s2.Find("td").Each(func(k int, s3 *goquery.Selection) {
// s3 here is a td element
if k == 0 {
return // This is the first TD in the row
}
fmt.Printf(s3.Text())
})
})
})

关于golang web scraper,忽略表格的特定单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30568318/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com