package main
import (
"fmt"
"github.com/gocolly/colly/v2"
"log"
"strings"
)
func url(c *colly.Collector) {
for count := 0; count < 3; count++ {
url := fmt.Sprintf("https://www.ebay.com/sch/i.html?_from=R40&_nkw=iPhone&_sacat=0&_pgn=%d&rt=nc", count) // Pagination
fmt.Println(url)
err := c.Visit(url)
if err != nil {
log.Println(err)
}
}
}
func main() {
var titleArray []string
var priceArray []string
c := colly.NewCollector(colly.UserAgent("Mozilla/5.0 (X11; Linux x86_64; rv:108.0) Gecko/20100101 Firefox/108.0"))
c.OnHTML(".s-item__title", func(element *colly.HTMLElement) {
element.ChildAttr("heading", "role")
titleArray = append(titleArray, element.Text)
})
c.OnHTML(".s-item__detail.s-item__detail--primary", func(element *colly.HTMLElement) {
element.ChildText(".s-item__price")
priceArray = append(priceArray, element.Text)
})
url(c)
defer func() {
for i := 0; i < len(titleArray); i++ {
titles := strings.TrimSpace(titleArray[i])
prices := strings.TrimSpace(priceArray[i])
fmt.Printf("Title | %s | Price %s \n", titles, prices)
}
}()
}
With my current code, it prints all the URLs and THEN scrapes, so if I wanted to scrape all 109 pages I would have to wait multiple minutes for the URLs to print and only then it would start to scrape.
for count := 0; count < 3; count++ { // page count
In this example I change the page count to only go to 3. It then prints the 3 urls, once it has finished printing the URLs it starts to scrape.
What should happen? Scrape the page, print the url. Go onto the next one.
I've tried adding: https://pkg.go.dev/github.com/gocolly/colly/v2#Collector.Wait
and https://pkg.go.dev/sync#example-WaitGroup
but have had no success with either, anyone know how to fix it?