【发布时间】: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) }
【问题讨论】: