Colly 如何获取子属性的值?

2024年 2月 11日 84.8k 0

colly - 如何获取子属性的值?

php小编西瓜为您介绍Colly这个强大的网络爬虫框架。Colly是一个使用Go语言编写的简单而灵活的爬虫框架,它提供了丰富的功能,包括获取HTML元素、提取数据以及处理请求和响应等。在使用Colly时,有时我们需要获取HTML元素的子属性的值,比如获取一个链接的href属性。那么,如何在Colly中获取子属性的值呢?接下来,我们将一一为您解答。

问题内容

这是我一直在 上工作的示例页面https://www.lazada.vn/-i1701980654-s7563711492.html

这是我想要获取的元素(产品标题)

...

lazmall

yierku 【free shipping miễn phí vận chuyển】giày nam mùa thu và mùa đông giày thường xu hướng nam thể thao tất cả các trận đấu giày da tăng chiều cao giày nam

...

登录后复制

我想获取 元素之间的文本值,即 yierku 【免费送货 miễn phí vận chuyển】giày n....

这是我迄今为止尝试过的

c := colly.NewCollector()
c.OnError(func(_ *colly.Response, err error) {
log.Println("Something went wrong:", err)
})
c.OnXML("/html/body", func(e *colly.XMLElement) {
child := e.ChildAttrs("div[4]/div/div[3]/div[2]/div/div[1]/div[3]/div/div/h1", "class")
fmt.Println(child)
//fmt.Println(child)
})

登录后复制

它给出了 pdp-mod-product-badge-title 的响应

当我尝试将其更改为

child := e.childattrs("div[4]/div/div[3]/div[2]/div/div[1]/div[3]/div/div/h1", "文本" )

它没有给我任何结果

解决方法

使用 func (*xmlelement) childtext相反。

package main

import (
"fmt"

"github.com/gocolly/colly/v2"
)

func main() {
c := colly.NewCollector()
c.OnError(func(_ *colly.Response, err error) {
fmt.Println("Something went wrong:", err)
})
c.OnXML("/html/body", func(e *colly.XMLElement) {
child := e.ChildText("div[4]/div/div[3]/div[2]/div/div[1]/div[3]/div/div/h1")
fmt.Println(child)
})
c.Visit("https://www.lazada.vn/-i1701980654-s7563711492.html")
// Output:
// Yierku 【Free Shipping Miễn phí vận chuyển】Giày nam mùa thu và mùa đông giày thường xu hướng nam thể thao tất cả các trận đấu giày da tăng chiều cao giày nam
}

登录后复制

以上就是Colly - 如何获取子属性的值?的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论