【问题标题】:Parsing nested elements using go-colly scraper使用 go-colly scraper 解析嵌套元素
【发布时间】:2023-01-04 19:49:51
【问题描述】:

我正在使用 go-colly 从网页中抓取数据:

我无法从这个嵌套的 HTML 元素中解析出 src 图像。

    c.OnHTML(".result-row", func(e *colly.HTMLElement) {
        qoquerySelection := e.DOM
        fmt.Println(qoquerySelection.Find("img").Attr("src"))
...

这个 .result-row 适用于很多事情,例如:

link := e.ChildAttrs("a", "href")

e.ChildText(".result-price")

如何获取嵌套图像src值?

【问题讨论】:

  • 你能在这里分享网页的网址吗?
  • 看起来像它的 craigslist。
  • 是的,任何 craigslist 搜索!

标签: go web-scraping go-colly


【解决方案1】:

如果我理解正确,我的解决方案应该可以满足您的需求。首先,让我展示代码:

package main

import (
    "fmt"
    "strings"

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

func main() {
    c := colly.NewCollector(colly.AllowedDomains(
        "santabarbara.craigslist.org",
    ))

    c.OnRequest(func(r *colly.Request) {
        r.Headers.Set("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36")
    })

    c.OnResponse(func(r *colly.Response) {
        fmt.Println("Response Code:", r.StatusCode)
    })

    c.OnHTML("img", func(h *colly.HTMLElement) {
        imgSrc := h.Attr("src")
        imgSrc = strings.Replace(imgSrc, "50x50c", "1200x900", 1)
        imgSrc = strings.Replace(imgSrc, "300x300", "1200x900", 1)
        imgSrc = strings.Replace(imgSrc, "600x450", "1200x900", 1)
        fmt.Println(imgSrc)
    })

    c.Visit("https://santabarbara.craigslist.org/apa/7570100710.html")
}

选择网页上的所有图像后,您必须将图标格式替换为最大的(在我们的例子中为 1200x900)。我在页面底部附近的 script 标签中看到了这些格式。
其余的应该非常简单。让我知道这是否解决了您的问题,或者您是否需要其他东西,谢谢!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-28
    • 2020-12-07
    • 2015-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多