vm.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  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. qu.Debug("附件为网页类型,过滤")
  93. continue
  94. }
  95. fileName := fmt.Sprintf("%s_%04d_%04d_%04d%s", time.Now().Format("20060102150405"), rand.Intn(9999),
  96. rand.Intn(9999), rand.Intn(9999), mtype.Extension())
  97. save2File := attachesDir + "/" + fileName
  98. fo, err := os.Create(save2File)
  99. if err != nil {
  100. qu.Debug(" 下载附件 生成文件 出错:", attach.Href, attach.FileName, save2File, err.Error())
  101. continue
  102. }
  103. fo.Write(bs)
  104. fo.Close()
  105. attach.FileName = fileName
  106. attach.FilePath = save2File
  107. attach.FileType = mtype.String()
  108. attach.FileSize = fmt.Sprintf("%.02fMB", float32(len(bs))/1024/1024)
  109. }
  110. //只过滤有效的附件
  111. newAttachesLinks := make([]*be.AttachLink, 0)
  112. for _, a := range v.AttachLinks {
  113. if a.FilePath != "" {
  114. newAttachesLinks = append(newAttachesLinks, a)
  115. }
  116. }
  117. v.AttachLinks = newAttachesLinks
  118. }
  119. // trunPage 翻页,需要作检查
  120. func trunPage(sc *be.SpiderConfig, delay int64, ctx context.Context) error {
  121. if sc.ListBodyCss == "" || (sc.ListNextPageCss == "" && sc.ListTurnPageJSCode == "") {
  122. return errors.New("当前爬虫配置,不具备翻页条件")
  123. }
  124. var runJs, result string = sc.ListTurnPageJSCode, ""
  125. if be.RegSpace.ReplaceAllString(runJs, "") == "" {
  126. runJs = fmt.Sprintf(`var link=document.querySelector("%s");if(link)link.click();""`, sc.ListNextPageCss)
  127. }
  128. qu.Debug("将要执行翻页的JS代码,", runJs)
  129. //TODO 1. 获取当前列表当前页的内容快照,以便与翻页后的结果对比
  130. var result1, result2 string
  131. var checkRunJs = fmt.Sprintf(`document.querySelector("%s").outerText`, sc.ListBodyCss)
  132. qu.Debug("获取当前页内容,执行的JS", checkRunJs)
  133. //获取当前页内容
  134. err := chromedp.Run(ctx, chromedp.Tasks{
  135. chromedp.Evaluate(checkRunJs, &result1),
  136. })
  137. if err != nil {
  138. qu.Debug("翻页检查1失败,", checkRunJs)
  139. return err
  140. }
  141. qu.Debug("第一页:", result1)
  142. qu.Debug("执行翻页JS:", runJs, delay)
  143. //执行翻页
  144. if runJs != "" {
  145. //可能就没有分页
  146. err = chromedp.Run(ctx, chromedp.Tasks{
  147. chromedp.Evaluate(runJs, &result),
  148. chromedp.Sleep(time.Duration(delay) * time.Millisecond),
  149. })
  150. if err != nil {
  151. qu.Debug("翻页操作失败,", runJs)
  152. return err
  153. }
  154. } else {
  155. return errors.New("trun page error ")
  156. }
  157. //获取翻页后内容
  158. err = chromedp.Run(ctx, chromedp.Tasks{
  159. chromedp.Evaluate(checkRunJs, &result2),
  160. })
  161. qu.Debug("第二页:", result2)
  162. if err != nil {
  163. qu.Debug("翻页检查2失败,", checkRunJs)
  164. return err
  165. }
  166. if result1 == "" || result2 == "" || result1 == result2 {
  167. return errors.New("翻页失败,两次翻页获取到的列表区域块不符合要求")
  168. }
  169. return nil
  170. }