packagemainimport ( "flag""github.com/go-rod/rod""log") const ( nationwideUrl="https://www.tianqi.com/chinacity.html") funcmain() { varcity=flag.String("c", "", "the config file") flag.Parse() url :=cityUrl(*city) ifurl=="" { log.Fatalf("url is empty") return } weatherData(url) } funcweatherData(urlstring) { page :=rod.New().MustConnect().MustPage(url) //直接使用选择器选择七天天气内容体projects :=page.MustElement("ul.weaul").MustElements("li") for_, project :=rangeprojects { var ( datestringweatherstringcentigradestring ) //获取日期ifok, dateEle, _ :=project.Has(".weaul_q"); ok { ifdateEle.MustHas(".fl") { date=dateEle.MustElement(".fl").MustText() } } for_, weatherEle :=rangeproject.MustElements(".weaul_z") { //如果存在span则是温度 否则是天气情况ifweatherEle.MustHas("span") { var ( startCstringendCstring ) //获取温度fork, cEle :=rangeweatherEle.MustElements("span") { ifk==0 { startC=cEle.MustText() } else { endC=cEle.MustText() } } centigrade=startC+"~"+endC } else { weather=weatherEle.MustText() } } log.Printf("日期:%s|天气:%s|摄氏度:%s℃\n", date, weather, centigrade) } } funccityUrl(citystring) string { cityMap :=make(map[string]string) page :=rod.New().MustConnect().MustPage(nationwideUrl) provinceProjects :=page.MustElement(".citybox").MustElements("h2") cityProjects :=page.MustElement(".citybox").MustElements("span") for_, section :=rangeprovinceProjects { cityMap[section.MustElement("a").MustText()] =section.MustElement("a").MustProperty("href").String() } for_, section :=rangecityProjects { for_, a :=rangesection.MustElements("a") { cityMap[a.MustText()] =a.MustProperty("href").String() } } ifhref, ok :=cityMap[city]; ok { returnhref+"7/" } return""}
说明:
1、新增文件夹
2、新增文件main.go
3、复制代码
4、初始化mod: go mod init weather
5、拉取依赖 go mod tidy
6、 运行:go run main.go -c 城市名 如 :go run main.go -c 河南
运行结果如下:
2023/06/29 16:39:30 日期:06-29|天气:阴|摄氏度:28~36℃
2023/06/29 16:39:30 日期:06-30|天气:小雨到中雨|摄氏度:26~29℃
2023/06/29 16:39:30 日期:07-01|天气:多云转阴|摄氏度:26~32℃
2023/06/29 16:39:30 日期:07-02|天气:小雨|摄氏度:27~32℃
2023/06/29 16:39:30 日期:07-03|天气:小雨转阴|摄氏度:27~34℃
2023/06/29 16:39:30 日期:07-04|天气:阴转雨|摄氏度:27~35℃
2023/06/29 16:39:30 日期:07-05|天气:小雨转多云|摄氏度:24~32℃