代码仅供参考学习使用。
[Golang] 纯文本查看 复制代码 package main
import (
"flag"
"github.com/go-rod/rod"
"log"
)
const (
nationwideUrl = "https://www.tianqi.com/chinacity.html"
)
func main() {
var city = flag.String("c", "", "the config file")
flag.Parse()
url := cityUrl(*city)
if url == "" {
log.Fatalf("url is empty")
return
}
weatherData(url)
}
func weatherData(url string) {
page := rod.New().MustConnect().MustPage(url)
//直接使用选择器选择七天天气内容体
projects := page.MustElement("ul.weaul").MustElements("li")
for _, project := range projects {
var (
date string
weather string
centigrade string
)
//获取日期
if ok, dateEle, _ := project.Has(".weaul_q"); ok {
if dateEle.MustHas(".fl") {
date = dateEle.MustElement(".fl").MustText()
}
}
for _, weatherEle := range project.MustElements(".weaul_z") {
//如果存在span则是温度 否则是天气情况
if weatherEle.MustHas("span") {
var (
startC string
endC string
)
//获取温度
for k, cEle := range weatherEle.MustElements("span") {
if k == 0 {
startC = cEle.MustText()
} else {
endC = cEle.MustText()
}
}
centigrade = startC + "~" + endC
} else {
weather = weatherEle.MustText()
}
}
log.Printf("日期:%s|天气:%s|摄氏度:%s℃\n", date, weather, centigrade)
}
}
func cityUrl(city string) 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 := range provinceProjects {
cityMap[section.MustElement("a").MustText()] = section.MustElement("a").MustProperty("href").String()
}
for _, section := range cityProjects {
for _, a := range section.MustElements("a") {
cityMap[a.MustText()] = a.MustProperty("href").String()
}
}
if href, ok := cityMap[city]; ok {
return href + "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℃
|