【问题标题】:Gocolly scraping only certain linksGocolly 只抓取某些链接
【发布时间】:2023-01-04 19:05:19
【问题描述】:

在抓取此链接enter link description here 时,我只想抓取库链接,但我编写的代码提取了所有链接,我无法过滤它。 (我正在解析 url 以供以后在 github api 中使用

http://api.github.com/repos/[username]/[reponame]

,所以我只需要路径部分,但我不想解析对我不起作用的链接以避免不必要的操作,所以我只需要库链接)

type repo struct {
Link string `json:"link"`
Name string `json:"name"`

}

allRepos := make([]repo, 0)
collector := colly.NewCollector(
    colly.AllowedDomains("github.com"))

collector.OnHTML("ul", func(e *colly.HTMLElement) {

    r := repo{}
    r.Link = e.ChildAttr("a", "href")
    url, _ := url.Parse(r.Link)

    repos := repo{
        Link: url.Path,
    }
    allRepos = append(allRepos, repos)
})

collector.OnRequest(func(r *colly.Request) {
    fmt.Println("Visiting", r.URL.String())
})
// Sends HTTP requests to the server
collector.Visit("https://github.com/avelino/awesome-go/blob/main/README.md")

fmt.Println(allRepos)
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", "\t")
//githubApi := "https://api.github.com/repos"
for _, repos := range allRepos {
    fmt.Println(repos.Link)
}

【问题讨论】:

    标签: go go-colly


    【解决方案1】:

    我能够管理你所需要的。让我与您分享我的代码:

    package main
    
    import (
        "fmt"
        "strings"
    
        "github.com/gocolly/colly/v2"
    )
    
    type Repo struct {
        Link string `json:"link"`
        Name string `json:"name"`
    }
    
    func main() {
        repos := []Repo{}
        c := colly.NewCollector(colly.AllowedDomains(
            "github.com",
        ))
    
        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)
        })
    
        // to get the "a" tag
        c.OnHTML("article>ul>li", func(h *colly.HTMLElement) {
            listItem := h.DOM
            for _, v := range listItem.Nodes {
                for _, a := range v.FirstChild.Attr {
                    if a.Key == "href" && strings.Contains(a.Val, "github.com") {
                        repos = append(repos, Repo{Link: a.Val, Name: v.FirstChild.FirstChild.Data})
                    }
                }
            }
        })
    
        c.Visit("https://github.com/avelino/awesome-go/blob/main/README.md")
    
        for _, v := range repos {
            fmt.Printf("%v	%v
    ", v.Name, v.Link)
        }
    }
    

    在上面的代码中,您可以看到我是如何设置回调来抓取 GitHub 存储库的。
    OnHTML方法中进行了相关修改。在这里,我们使用了 jQuery 选择器来获取 articleul 标签下方的所有 li。然后,您必须遍历底层节点并获得始终是 a 标记的 FirstChild。您必须获取 href 属性并将其附加到刚刚找到的 repos 变量。

    笔记:因为您只关心 GitHub 存储库,所以我在 if 结构中添加了一个子句,以排除不相关的链接。如果您打算删除此链接,请注意这些链接,因为您还必须处理页面的导航链接,例如page#section-1

    我希望这能解决您的问题。如果您已经自己找到了另一个解决方案,请告诉我或者分享您的解决方案!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多