vm.go 5.1 KB

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