Featured image of post bobo

bobo

这是一个副标题

  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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
package main

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"net/url"
	"os"
	"path/filepath"
	"strings"
	"time"

	"github.com/gocolly/colly"
	"github.com/schollz/progressbar/v3"
)

var logger *log.Logger
var consoleLogger *log.Logger

func init() {
	// 初始化日志文件
	logFile, err := os.OpenFile("crawler.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	if err != nil {
		fmt.Printf("无法创建日志文件: %v\n", err)
		os.Exit(1)
	}
	// 日志仅输出到文件
	logger = log.New(logFile, "", log.Ldate|log.Ltime|log.Lshortfile)
	// 终端日志
	consoleLogger = log.New(os.Stdout, "", log.Ldate|log.Ltime)
}

func main() {
	// 获取 Cookie
	cookie, err := getCookie("http://res.cxxy.truraly.fun?login=zsxq:1145141919810")
	if err != nil {
		consoleLogger.Printf("获取 Cookie 失败: %v", err)
		os.Exit(1)
	}
	consoleLogger.Println("成功获取 Cookie")

	// 创建 Colly 收集器
	c := colly.NewCollector(
		colly.AllowedDomains("res.cxxy.truraly.fun"),
		colly.Async(true),
	)

	// 设置请求间隔
	c.Limit(&colly.LimitRule{
		DomainGlob:  "*",
		Parallelism: 2,
		Delay:       2 * time.Second,
	})

	// 设置请求头和 Cookie
	c.OnRequest(func(r *colly.Request) {
		r.Headers.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
		r.Headers.Set("Cookie", cookie)
		logger.Printf("正在访问: %s", r.URL.String())
	})

	// 仅记录响应到日志文件
	c.OnResponse(func(r *colly.Response) {
		logger.Printf("响应状态码: %d", r.StatusCode)
		logger.Printf("响应内容: %s", string(r.Body))
	})

	// 检查页面是否加载成功
	c.OnHTML("html", func(e *colly.HTMLElement) {
		logger.Printf("成功解析页面: %s", e.Request.URL.String())
	})

	// 处理文件夹
	c.OnHTML("a[href*='/?get=basic']", func(e *colly.HTMLElement) {
		link := e.Request.AbsoluteURL(e.Attr("href"))
		name, err := url.QueryUnescape(e.Text)
		if err != nil {
			logger.Printf("解码文件夹名称失败: %v", err)
			return
		}
		if name == ".." || strings.Contains(link, "get=logout") {
			logger.Printf("忽略链接: %s %s", name, link)
			return
		}
		logger.Printf("发现文件夹: %s URL: %s", name, link)

		// 创建本地文件夹
		localPath := filepath.Join("downloads", strings.ReplaceAll(strings.Split(link, "?get=basic")[0], "http://res.cxxy.truraly.fun/", ""))
		err = os.MkdirAll(localPath, 0755)
		if err != nil {
			logger.Printf("创建文件夹失败: %v", err)
			return
		}
		// 递归访问文件夹
		visitURL := link
		if !strings.Contains(visitURL, "?get=basic") {
			visitURL = link + "?get=basic"
		}
		err = c.Visit(visitURL)
		if err != nil {
			logger.Printf("访问文件夹失败: %v", err)
		}
	})

	// 处理文件
	c.OnHTML("a[href]", func(e *colly.HTMLElement) {
		link := e.Request.AbsoluteURL(e.Attr("href"))
		name, err := url.QueryUnescape(e.Text)
		if err != nil {
			logger.Printf("解码文件名称失败: %v", err)
			return
		}
		if strings.Contains(link, "get=login") || strings.Contains(link, "get=logout") || strings.Contains(link, "?get=basic") {
			return
		}
		if isFile(link) {
			logger.Printf("发现文件: %s URL: %s", name, link)
			localPath := filepath.Join("downloads", strings.ReplaceAll(e.Request.URL.Path, "/", string(os.PathSeparator)))
			localFilePath := filepath.Join(localPath, name)
			if _, err := os.Stat(localFilePath); !os.IsNotExist(err) {
				consoleLogger.Printf("文件已存在,跳过: %s", localFilePath)
				return
			}
			err = os.MkdirAll(filepath.Dir(localFilePath), 0755)
			if err != nil {
				logger.Printf("创建文件目录失败: %v", err)
				return
			}
			consoleLogger.Printf("开始下载: %s", name)
			err = downloadFile(link, localFilePath, cookie)
			if err != nil {
				consoleLogger.Printf("下载失败: %s, 错误: %v", name, err)
			} else {
				consoleLogger.Printf("文件已保存: %s", localFilePath)
			}
		}
	})

	// 错误处理
	c.OnError(func(r *colly.Response, err error) {
		logger.Printf("请求失败: %s, 状态码: %d, 错误: %v", r.Request.URL, r.StatusCode, err)
		logger.Printf("响应内容: %s", string(r.Body))
	})

	// 开始爬取
	consoleLogger.Println("开始爬取...")
	err = c.Visit("http://res.cxxy.truraly.fun/%E6%88%90%E8%B4%A4%E6%9C%9F%E6%9C%AB%E5%A4%8D%E4%B9%A0%E8%B5%84%E6%96%99/?get=basic")
	if err != nil {
		consoleLogger.Printf("初始请求失败: %v", err)
	}

	c.Wait()
	consoleLogger.Println("爬取完成")
}

// 获取 Cookie
func getCookie(loginURL string) (string, error) {
	client := &http.Client{
		CheckRedirect: func(req *http.Request, via []*http.Request) error {
			return http.ErrUseLastResponse // 阻止自动重定向以获取 Cookie
		},
	}
	req, err := http.NewRequest("GET", loginURL, nil)
	if err != nil {
		return "", fmt.Errorf("创建登录请求失败: %v", err)
	}
	req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")

	resp, err := client.Do(req)
	if err != nil {
		return "", fmt.Errorf("登录请求失败: %v", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusFound {
		return "", fmt.Errorf("登录失败,状态码: %d", resp.StatusCode)
	}

	cookies := resp.Header["Set-Cookie"]
	if len(cookies) == 0 {
		return "", fmt.Errorf("未找到 Cookie")
	}

	return strings.Join(cookies, "; "), nil
}

// 判断是否为文件
func isFile(url string) bool {
	extensions := []string{".pdf", ".jpg", ".png", ".zip", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".txt", ".mp4", ".mp3", ".rar", ".7z"}
	for _, ext := range extensions {
		if strings.HasSuffix(strings.ToLower(url), ext) {
			return true
		}
	}
	return false
}

// 下载文件(带进度条和重试机制)
func downloadFile(url, localPath, cookie string) error {
	const maxRetries = 3
	for attempt := 1; attempt <= maxRetries; attempt++ {
		client := &http.Client{}
		req, err := http.NewRequest("GET", url, nil)
		if err != nil {
			return fmt.Errorf("创建请求失败: %v", err)
		}
		req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
		req.Header.Set("Cookie", cookie)

		resp, err := client.Do(req)
		if err != nil {
			logger.Printf("下载尝试 %d/%d 失败: %v", attempt, maxRetries, err)
			if attempt == maxRetries {
				return fmt.Errorf("发送请求失败: %v", err)
			}
			time.Sleep(time.Second * time.Duration(attempt))
			continue
		}
		defer resp.Body.Close()

		if resp.StatusCode != http.StatusOK {
			logger.Printf("下载尝试 %d/%d 失败,状态码: %d", attempt, maxRetries, resp.StatusCode)
			if attempt == maxRetries {
				return fmt.Errorf("下载失败,状态码: %d", resp.StatusCode)
			}
			time.Sleep(time.Second * time.Duration(attempt))
			continue
		}

		// 创建文件
		out, err := os.Create(localPath)
		if err != nil {
			return fmt.Errorf("创建文件失败: %v", err)
		}
		defer out.Close()

		// 创建进度条
		bar := progressbar.NewOptions64(
			resp.ContentLength,
			progressbar.OptionSetDescription(filepath.Base(localPath)),
			progressbar.OptionSetWidth(30),
			progressbar.OptionShowBytes(true),
			progressbar.OptionSetTheme(progressbar.Theme{
				Saucer:        "=",
				SaucerHead:    ">",
				SaucerPadding: " ",
				BarStart:      "[",
				BarEnd:        "]",
			}),
		)

		// 使用 io.TeeReader 将读取数据同时写入文件和更新进度条
		_, err = io.Copy(out, io.TeeReader(resp.Body, bar))
		if err != nil {
			logger.Printf("下载尝试 %d/%d 失败: %v", attempt, maxRetries, err)
			if attempt == maxRetries {
				return fmt.Errorf("写入文件失败: %v", err)
			}
			time.Sleep(time.Second * time.Duration(attempt))
			continue
		}
		return nil
	}
	return nil
}
Licensed under CC BY-NC-SA 4.0