【问题标题】:How can I get the name of a seller on a specific website using golang?如何使用 golang 获取特定网站上的卖家名称?
【发布时间】:2022-08-17 18:53:53
【问题描述】:

我正在制作一个网络爬虫。给定一个特定的网页,我试图获取位于右上角的卖家名称(在这个 olx 网站的示例中,您可以看到卖家的名称是 Ionut)。当我运行下面的代码时,它应该在 index.csv 文件中写入名称,但该文件是空的。我认为问题出在 HTML 解析器上,尽管对我来说它看起来不错。

package main

import (
    \"encoding/csv\"
    \"fmt\"
    \"log\"
    \"os\"
    \"path/filepath\"

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

func main() {
    //setting up the file where we store collected data
    fName := filepath.Join(\"D:\\\\\", \"go projects\", \"cwst go\", \"CWST-GO\", \"target folder\", \"index.csv\")
    file, err := os.Create(fName)
    if err != nil {
        log.Fatalf(\"Could not create file, error :%q\", err)
    }
    defer file.Close()
    //writer that writes the collected data into our file
    writer := csv.NewWriter(file)
    //after the file is written, what it is in the buffer goes in writer and then passed to file
    defer writer.Flush()

    //collector
    c := colly.NewCollector(
        colly.AllowedDomains(\"https://www.olx.ro/\"),
    )

    //HTML parser
    c.OnHTML(\".css-1fp4ipz\", func(e *colly.HTMLElement) { //div class that contains wanted info

        writer.Write([]string{
            e.ChildText(\"h4\"), //specific tag of the info
        })
    })

    fmt.Printf(\"Scraping page :  \")
    c.Visit(\"https://www.olx.ro/d/oferta/bmw-xdrixe-seria-7-2020-71000-tva-IDgp7iN.html\")

    log.Printf(\"\\n\\nScraping Complete\\n\\n\")
    log.Println(c)

}
  • 我建议你从小处着手。从您的 sn-p 中丢弃 CSV 代码,并将大量调试添加到定位必要 HTML 元素的部分。请注意,今天的网络是一个糟糕的^W复杂的地方,所以您在浏览器呈现的页面中看到的元素可能是由您的浏览器、客户端中运行的 JS 代码创建的,所以所有这些@ 987654322@s 可能会在每次页面加载时重新生成,有不同的ID等等。所以你需要耐心地调试这些东西。
  • 另一方面,如果一个页面在客户端 JS 上很重,你可能会从另一个角度攻击它:页面很可能通过向站点的后端服务发出一个或多个请求来获取要呈现的数据,并且在大多数情况下,它以机器可读的格式交付,例如 JSON。如果您能够收集必要的 cookie/auth 令牌等,您可以分析页面的代码以查看它对后端服务的哪些调用。当今浏览器的 DevTools 极大地帮助了此类活动。

标签: go web web-scraping


【解决方案1】:

您无需在允许的域中添加https/

c := colly.NewCollector(
    colly.AllowedDomains("www.olx.ro"),
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-13
    • 1970-01-01
    • 2012-12-09
    • 2016-09-13
    • 2014-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多