使用chrome采集网页HTML
(urlStr string, bookIdentify string)
| 254 | |
| 255 | // 使用chrome采集网页HTML |
| 256 | func CrawlByChrome(urlStr string, bookIdentify string) (cont string, err error) { |
| 257 | if strings.Contains(strings.ToLower(urlStr), "bookstack") { |
| 258 | return |
| 259 | } |
| 260 | var ( |
| 261 | args []string |
| 262 | b []byte |
| 263 | folder string |
| 264 | ) |
| 265 | |
| 266 | name := beego.AppConfig.DefaultString("chrome", "chromium-browser") |
| 267 | ok, _ := beego.AppConfig.Bool("puppeteer") |
| 268 | selector, isScreenshot := ScreenShotProjects.Load(bookIdentify) |
| 269 | if ok || isScreenshot { |
| 270 | name = "node" // 读取截屏信息 |
| 271 | args = []string{"crawl.js", "--url", urlStr} |
| 272 | if isScreenshot { |
| 273 | folder = fmt.Sprintf("cache/screenshots/" + bookIdentify + "/" + MD5Sub16(urlStr)) |
| 274 | os.MkdirAll(folder, os.ModePerm) |
| 275 | args = append(args, "--folder", folder, "--selector", selector.(string)) |
| 276 | } |
| 277 | } else { // chrome |
| 278 | args = []string{"--headless", "--disable-gpu", "--dump-dom", "--no-sandbox", urlStr} |
| 279 | } |
| 280 | cmd := exec.Command(name, args...) |
| 281 | expire := 2 * httpTimeout |
| 282 | if isScreenshot { |
| 283 | expire = 10 * httpTimeout |
| 284 | } |
| 285 | time.AfterFunc(expire, func() { |
| 286 | if cmd.Process != nil && cmd.Process.Pid != 0 { |
| 287 | cmd.Process.Kill() |
| 288 | } |
| 289 | }) |
| 290 | |
| 291 | b, err = cmd.Output() |
| 292 | cont = string(b) |
| 293 | |
| 294 | if isScreenshot { |
| 295 | pngFile := filepath.Join(folder, "screenshot.png") |
| 296 | jsonFile := filepath.Join(folder, "screenshot.json") |
| 297 | imagesMap := cropScreenshot(selector.(string), jsonFile, pngFile) |
| 298 | if len(imagesMap) > 0 { |
| 299 | doc, errDoc := goquery.NewDocumentFromReader(strings.NewReader(cont)) |
| 300 | if errDoc != nil { |
| 301 | beego.Error(errDoc) |
| 302 | } else { |
| 303 | for ele, images := range imagesMap { |
| 304 | doc.Find(ele).Each(func(i int, selection *goquery.Selection) { |
| 305 | if img, ok := images[i]; ok { |
| 306 | htmlStr := fmt.Sprintf(`<div><img src="$%v"/></div>`, img) |
| 307 | selection.AfterHtml(htmlStr) |
| 308 | selection.Remove() |
| 309 | } |
| 310 | }) |
| 311 | } |
| 312 | cont, err = doc.Find("body").Html() |
| 313 | } |
no test coverage detected