vm.go 4.8 KB

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