vm.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. package vm
  2. import (
  3. "bytes"
  4. "context"
  5. _ "embed"
  6. "errors"
  7. "fmt"
  8. "io/ioutil"
  9. qu "jygit.jydev.jianyu360.cn/data_processing/common_utils"
  10. "math/rand"
  11. "net/http"
  12. "os"
  13. "regexp"
  14. be "spider_creator/backend"
  15. "strings"
  16. "text/template"
  17. "time"
  18. "github.com/chromedp/chromedp"
  19. "github.com/gabriel-vasile/mimetype"
  20. )
  21. const (
  22. MAX_TRUN_PAGE = 1000
  23. VERIVY_MAX_TRUN_PAGE = 3
  24. )
  25. var (
  26. Reg_Date = regexp.MustCompile(`\d`)
  27. )
  28. type (
  29. //单一任务
  30. VM struct {
  31. attachesDir string
  32. dnf be.EventNotifyFace
  33. }
  34. //执行单元
  35. Worker struct {
  36. vm *VM
  37. baseCancel, incCancel context.CancelFunc
  38. ctx context.Context
  39. js string
  40. contentDelay int64
  41. }
  42. )
  43. var (
  44. //go:embed load_list_items.js
  45. loadListItemsJS string
  46. //go:embed load_content.js
  47. loadContentJS string
  48. )
  49. // renderJavascriptCoder
  50. func renderJavascriptCoder(tpl string, sc *be.SpiderConfig) string {
  51. t, err := template.New("").Parse(tpl)
  52. if err != nil {
  53. qu.Debug("创建JS代码模板失败", err.Error())
  54. return ""
  55. }
  56. buf := new(bytes.Buffer)
  57. err = t.Execute(buf, sc)
  58. if err != nil {
  59. qu.Debug("执行JS代码模板失败", err.Error())
  60. return ""
  61. }
  62. return buf.String()
  63. }
  64. // downloadAttaches 下载附件
  65. func downloadAttaches(v *be.ResultItem, attachesDir string) {
  66. client := &http.Client{
  67. Timeout: 30 * time.Second,
  68. }
  69. for _, attach := range v.AttachLinks {
  70. qu.Debug("准备下载附件,", attach.Href, attach.Title)
  71. req, err := http.NewRequest("GET", attach.Href, nil)
  72. if err != nil {
  73. qu.Debug(" 下载附件 构建req 出错:", attach.Href, attach.FileName, err.Error())
  74. continue
  75. }
  76. req.Header.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36")
  77. resp, err := client.Do(req)
  78. if err != nil {
  79. qu.Debug(" 下载附件 发送请求 出错:", attach.Href, attach.FileName, err.Error())
  80. continue
  81. }
  82. bs, err := ioutil.ReadAll(resp.Body)
  83. if err != nil {
  84. qu.Debug(" 下载附件 下载 出错:", attach.Href, attach.FileName, err.Error())
  85. continue
  86. }
  87. resp.Body.Close()
  88. //TODO 写入文件
  89. mtype := mimetype.Detect(bs)
  90. //不要HTML网页
  91. if strings.Contains(strings.ToLower(mtype.String()), "html") {
  92. continue
  93. }
  94. fileName := fmt.Sprintf("%s_%04d_%04d_%04d%s", time.Now().Format("20060102150405"), rand.Intn(9999),
  95. rand.Intn(9999), rand.Intn(9999), mtype.Extension())
  96. save2File := attachesDir + "/" + fileName
  97. fo, err := os.Create(save2File)
  98. if err != nil {
  99. qu.Debug(" 下载附件 生成文件 出错:", attach.Href, attach.FileName, save2File, err.Error())
  100. continue
  101. }
  102. fo.Write(bs)
  103. fo.Close()
  104. attach.FileName = fileName
  105. attach.FilePath = save2File
  106. attach.FileType = mtype.String()
  107. attach.FileSize = fmt.Sprintf("%.02fMB", float32(len(bs))/1024/1024)
  108. }
  109. //只过滤有效的附件
  110. newAttachesLinks := make([]*be.AttachLink, 0)
  111. for _, a := range v.AttachLinks {
  112. if a.FilePath != "" {
  113. newAttachesLinks = append(newAttachesLinks, a)
  114. }
  115. }
  116. v.AttachLinks = newAttachesLinks
  117. }
  118. // trunPage 翻页,需要作检查
  119. func trunPage(sc *be.SpiderConfig, delay int64, ctx context.Context) error {
  120. if sc.ListBodyCss == "" || (sc.ListNextPageCss == "" && sc.ListTurnPageJSCode == "") {
  121. return errors.New("当前爬虫配置,不具备翻页条件")
  122. }
  123. var runJs, result string = sc.ListTurnPageJSCode, ""
  124. if be.RegSpace.ReplaceAllString(runJs, "") == "" {
  125. runJs = fmt.Sprintf(`var link=document.querySelector("%s");if(link)link.click();""`, sc.ListNextPageCss)
  126. }
  127. qu.Debug("将要执行翻页的JS代码,", runJs)
  128. //TODO 1. 获取当前列表当前页的内容快照,以便与翻页后的结果对比
  129. var result1, result2 string
  130. var checkRunJs = fmt.Sprintf(`document.querySelector("%s").outerText`, sc.ListBodyCss)
  131. qu.Debug("获取当前页内容,执行的JS", checkRunJs)
  132. //获取当前页内容
  133. err := chromedp.Run(ctx, chromedp.Tasks{
  134. chromedp.Evaluate(checkRunJs, &result1),
  135. })
  136. if err != nil {
  137. qu.Debug("翻页检查1失败,", checkRunJs)
  138. return err
  139. }
  140. qu.Debug("第一页:", result1)
  141. qu.Debug("执行翻页JS:", runJs, delay)
  142. //执行翻页
  143. if runJs != "" {
  144. //可能就没有分页
  145. err = chromedp.Run(ctx, chromedp.Tasks{
  146. chromedp.Evaluate(runJs, &result),
  147. chromedp.Sleep(time.Duration(delay) * time.Millisecond),
  148. })
  149. if err != nil {
  150. qu.Debug("翻页操作失败,", runJs)
  151. return err
  152. }
  153. } else {
  154. return errors.New("trun page error ")
  155. }
  156. //获取翻页后内容
  157. err = chromedp.Run(ctx, chromedp.Tasks{
  158. chromedp.Evaluate(checkRunJs, &result2),
  159. })
  160. qu.Debug("第二页:", result2)
  161. if err != nil {
  162. qu.Debug("翻页检查2失败,", checkRunJs)
  163. return err
  164. }
  165. if result1 == "" || result2 == "" || result1 == result2 {
  166. return errors.New("翻页失败,两次翻页获取到的列表区域块不符合要求")
  167. }
  168. return nil
  169. }