1 回答

TA貢獻(xiàn)1821條經(jīng)驗(yàn) 獲得超5個(gè)贊
錯(cuò)誤在地圖分配中。管理如此嵌套的結(jié)構(gòu)非常困難,但我找到了成功處理它的方法。讓我展示代碼:
package main
import (
"encoding/json"
"fmt"
"strconv"
"time"
"github.com/gocolly/colly/v2"
)
type contest struct{}
func AtcoderFunc(contests map[string]map[string]map[string]string) {
collector := colly.NewCollector(
colly.AllowedDomains("atcoder.jp", "www.atcoder.jp"),
)
format := "2006-01-02 15:04:05-0700"
loc, _ := time.LoadLocation("Asia/Calcutta")
contests["UpcomingContest"] = make(map[string]map[string]string)
for i := 1; i < 3; i++ {
rawI := strconv.Itoa(i)
contests["UpcomingContest"][rawI] = make(map[string]string)
contestSelTime := fmt.Sprintf("#contest-table-upcoming div div table tbody tr:nth-child(%d) td:nth-child(1) a", i+1)
contestSelName := fmt.Sprintf("#contest-table-upcoming div div table tbody tr:nth-child(%d) td:nth-child(2)", i)
// for contest name
collector.OnHTML(contestSelName, func(element *colly.HTMLElement) {
contestName := element.ChildText("a")
contests["UpcomingContest"][rawI]["Name"] = contestName
})
// for contestTime
collector.OnHTML(contestSelTime, func(element *colly.HTMLElement) {
ContestStartTime := element.ChildText("time")
parsed_time, _ := time.Parse(format, ContestStartTime)
IST_time := parsed_time.In(loc)
contests["UpcomingContest"][rawI]["Time"] = fmt.Sprint(IST_time)
})
}
collector.OnRequest(func(r *colly.Request) {
fmt.Println("Visiting", r.URL.String())
})
collector.Visit("https://atcoder.jp/contests")
}
func main() {
contests := make(map[string]map[string]map[string]map[string]string)
contests["AtCoder"] = make(map[string]map[string]map[string]string)
AtcoderFunc(contests["AtCoder"])
data, _ := json.MarshalIndent(contests, "", " ")
fmt.Println(string(data))
}
我或多或少保留了你的結(jié)構(gòu)。除了解決這個(gè)問(wèn)題之外,我通過(guò)更改一些名稱并刪除未使用的語(yǔ)句來(lái)稍微重構(gòu)了您的示例。最后,我使用MarshalIndent函數(shù)美化了打印到終端上的 JSON 字符串。
讓我知道是否也適合你!
- 1 回答
- 0 關(guān)注
- 96 瀏覽
添加回答
舉報(bào)