1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
| package main
import ( "database/sql" "fmt" "github.com/PuerkitoBio/goquery" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" "net/http" "regexp" "strconv" "strings" )
const ( USERNAME = "root" PASSWORD = "123456" HOST = "127.0.0.1" PORT = "3306" DBNAME = "spider" )
type MovieData struct { Title string `json:"title"` Director string `json:"Director"` Picture string `json:"Picture"` Actor string `json:"Actor"` Year string `json:"Year"` Score string `json:"Score"` Quote string `json:"Quote"` }
var DB *sql.DB
func InitDBBySQL() { path := strings.Join([]string{USERNAME, ":", PASSWORD, "@tcp(", HOST, ":", PORT, ")/", DBNAME, "?charset=utf8"}, "") DB, _ = sql.Open("mysql", path) DB.SetConnMaxLifetime(10) DB.SetMaxIdleConns(5) if err := DB.Ping(); err != nil { fmt.Println("opon database fail") return } fmt.Println("connect success") }
var gormdb *gorm.DB
func InitDBByGORM() { var err error path := strings.Join([]string{USERNAME, ":", PASSWORD, "@tcp(", HOST, ":", PORT, ")/", DBNAME, "?charset=utf8"}, "") gormdb, err = gorm.Open("mysql", path) if err != nil { panic(err) } _ = gormdb.AutoMigrate(&NewD{}) sqlDB := gormdb.DB() sqlDB.SetMaxIdleConns(10) sqlDB.SetMaxOpenConns(100) fmt.Println("connect success") }
func main() { InitDBByGORM() for i := 0; i < 10; i++ { fmt.Printf("正在爬取第 %d 页的信息\n", i) Spider(strconv.Itoa(i * 25)) } }
func Spider(page string) { client := http.Client{} URL := "https://movie.douban.com/top250?start=" + page req, err := http.NewRequest("GET", URL, nil) if err != nil { fmt.Println("构造Get请求失败: ", err) } req.Header.Set("Connection", "keep-alive") req.Header.Set("Pragma", "no-cache") req.Header.Set("Cache-Control", "no-cache") req.Header.Set("Upgrade-Insecure-Requests", "1") req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36") req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9") req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9")
resp, err := client.Do(req) if err != nil { fmt.Println("发送请求失败: ", err) } defer resp.Body.Close()
doc, err := goquery.NewDocumentFromReader(resp.Body) if err != nil { fmt.Println("解析失败", err) }
doc.Find("#content > div > div.article > ol > li"). Each(func(i int, s *goquery.Selection) { var data MovieData title := s.Find("div > div.info > div.hd > a > span:nth-child(1)").Text() img := s.Find("div > div.pic > a > img") imgTmp, ok := img.Attr("src") info := s.Find("div > div.info > div.bd > p:nth-child(1)").Text() score := s.Find("div > div.info > div.bd > div > span.rating_num").Text() quote := s.Find("div > div.info > div.bd > p.quote > span").Text() if ok { director, actor, year := InfoSpite(info) data.Title = title data.Director = director data.Actor = actor data.Picture = imgTmp data.Year = year data.Score = score data.Quote = quote if InsertDataByGORM(data) { fmt.Printf("插入成功:%+v\n", data) } else { fmt.Printf("插入失败:%+v\n", data) } } })
}
func InfoSpite(info string) (director, actor, year string) { directorRe, _ := regexp.Compile(`导演:(.*)主演:`) director = string(directorRe.Find([]byte(info)))
actorRe, _ := regexp.Compile(`主演:(.*)`) actor = string(actorRe.Find([]byte(info)))
yearRe, _ := regexp.Compile(`(\d+)`) year = string(yearRe.Find([]byte(info))) return }
func InsertDataBySQL(data MovieData) bool { tx, err := DB.Begin() if err != nil { fmt.Println("开启数据库事务DB.Begin()失败:", err) return false } stmt, err := tx.Prepare("Insert INTO douban_movie(`Title`, `Director`, `Picture`, `Actor`, `Year`, `Score`, `Quote`) VALUES (?, ?, ?, ?, ?, ?, ?)") if err != nil { fmt.Println("数据准备tx.Prepare失败:", err) return false } _, err = stmt.Exec(data.Title, data.Director, data.Picture, data.Actor, data.Year, data.Score, data.Quote) if err != nil { fmt.Println("数据插入stmt.Exec失败:", err) return false } tx.Commit() return true }
type NewD struct { gorm.Model Title string `gorm:"type:varchar(255);not null;"` Director string `gorm:"type:varchar(256);not null;"` Picture string `gorm:"type:varchar(256);not null;"` Actor string `gorm:"type:varchar(256);not null;"` Year string `gorm:"type:varchar(256);not null;"` Score string `gorm:"type:varchar(256);not null;"` Quote string `gorm:"type:varchar(256);not null;"` }
func InsertDataByGORM(data MovieData) bool { NewA := NewD{ Title: data.Title, Director: data.Director, Picture: data.Picture, Actor: data.Actor, Year: data.Year, Score: data.Score, Quote: data.Quote, } err := gormdb.Create(&NewA).Error if err != nil { return false } return true }
|