Go Colly - Access URL in for loop

王林
Release: 2024-02-06 10:51:03
forward
980 people have browsed it

Go Colly - 在 for 循环中访问 URL

Question content

I have an example where I should visit multiple links and extract information from them. The problem is that when I use "colly.Visit(URL)" my visits increase. Example:

package main

import (
    "fmt"

    "github.com/gocolly/colly"
)

func main() {

    CATETORIES := []string{
        "cate1",
        "cate2",
        "cate3",
    }

    c := colly.NewCollector()

    for _, cate := range CATETORIES {

        c.OnRequest(func(r *colly.Request) {
            fmt.Println("Visiting categories", r.URL)
        })

        c.Visit(cate)
    }
}
Copy after login

This will print:

Visiting categories http://cate1  
Visiting categories http://cate2
Visiting categories http://cate2
Visiting categories http://cate3
Visiting categories http://cate3
Visiting categories http://cate3
Copy after login

I tried initializing colly after each iteration, which worked fine - then the order was: access category http://cate1, access category http://cate2, access category http://cate3 But doing this I will lose my login session.. Any suggestions?


Correct Answer


You are adding a new OnRequest handler for each loop iteration. Configure the handler outside the loop:

func main() {

  CATETORIES := []string{
    "cate1",
    "cate2",
    "cate3",
  }

  c := colly.NewCollector()

  c.OnRequest(func(r *colly.Request) {
    fmt.Println("Visiting categories", r.URL)
  })

  for _, cate := range CATETORIES {
    c.Visit(cate)
  }
}
Copy after login

The above is the detailed content of Go Colly - Access URL in for loop. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!