From fec85b2b304236a9f48090e33b8f611986385b77 Mon Sep 17 00:00:00 2001 From: Journey <52627267+chengazhen@users.noreply.github.com> Date: Sat, 20 Sep 2025 00:16:07 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0=E5=9B=BE=E7=89=87?= =?UTF-8?q?=E4=B8=8A=E4=BC=A0=E9=AA=8C=E8=AF=81=E4=B8=8E=E8=B6=85=E6=97=B6?= =?UTF-8?q?=E5=A4=84=E7=90=86=E5=8A=9F=E8=83=BD=20(#115)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit (cherry picked from commit 651b1578ae341f0a5cbb1447d483cc8954f7e5bc) Co-authored-by: chengchongzhen <15939054361@163.com> --- xiaohongshu/publish.go | 43 +++++++++++++++++++++++++++++++++++++++--- 1 file changed, 40 insertions(+), 3 deletions(-) diff --git a/xiaohongshu/publish.go b/xiaohongshu/publish.go index 67a20ba..e07a595 100644 --- a/xiaohongshu/publish.go +++ b/xiaohongshu/publish.go @@ -3,6 +3,7 @@ package xiaohongshu import ( "context" "log/slog" + "os" "strings" "time" @@ -98,16 +99,52 @@ func (p *PublishAction) Publish(ctx context.Context, content PublishImageContent func uploadImages(page *rod.Page, imagesPaths []string) error { pp := page.Timeout(30 * time.Second) + // 验证文件路径有效性 + for _, path := range imagesPaths { + if _, err := os.Stat(path); os.IsNotExist(err) { + return errors.Wrapf(err, "图片文件不存在: %s", path) + } + } + // 等待上传输入框出现 uploadInput := pp.MustElement(".upload-input") // 上传多个文件 uploadInput.MustSetFiles(imagesPaths...) - // 等待上传完成 - time.Sleep(3 * time.Second) + // 等待并验证上传完成 + return waitForUploadComplete(pp, len(imagesPaths)) +} - return nil +// waitForUploadComplete 等待并验证上传完成 +func waitForUploadComplete(page *rod.Page, expectedCount int) error { + maxWaitTime := 60 * time.Second + checkInterval := 500 * time.Millisecond + start := time.Now() + + slog.Info("开始等待图片上传完成", "expected_count", expectedCount) + + for time.Since(start) < maxWaitTime { + // 使用具体的pr类名检查已上传的图片 + uploadedImages, err := page.Elements(".img-preview-area .pr") + + slog.Info("uploadedImages", "uploadedImages", uploadedImages) + + if err == nil { + currentCount := len(uploadedImages) + slog.Info("检测到已上传图片", "current_count", currentCount, "expected_count", expectedCount) + if currentCount >= expectedCount { + slog.Info("所有图片上传完成", "count", currentCount) + return nil + } + } else { + slog.Debug("未找到已上传图片元素") + } + + time.Sleep(checkInterval) + } + + return errors.New("上传超时,请检查网络连接和图片大小") } func submitPublish(page *rod.Page, title, content string, tags []string) error {