【问题标题】:Dumping DOM using chrome headless and GO使用 chrome headless 和 GO 转储 DOM
【发布时间】:2019-02-07 11:34:12
【问题描述】:

我想做什么:

使用 chrome headlessgo 渲染 dom。

我查看了aqautone 的代码以了解如何使用 chrome headless 来满足我的需求。

问题

问题是,如果我添加许多网址,它只会超时打印Dumping dom timed out,而目前它只打印两个网址:

<html><head></head><body></body></html>
<html><head></head><body></body></html>
<html><head></head><body></body></html>
<html><head></head><body></body></html>
Checking  bingBot
1.73 URL : https://www.facebook.com
<html><head></head><body></body></html>
Checking  yahooBot
1.75 URL : https://www.facebook.com
Checking  bingBot
1.74 URL : https://www.google.com
Checking  googleBot
1.75 URL : https://www.google.com
Checking  googleBot
1.76 URL : https://www.facebook.com
<html><head></head><body></body></html>
Checking  yahooBot
1.76 URL : https://www.google.com
Total time taken 1.78s elapsed

这是我的代码:Playground (但是,由于那里没有 chrome exec,所以没有意义)

如果你不想去游乐场:

package main

import (
    "context"
    "fmt"
    "io"
    "log"
    "os"
    "os/exec"
    "sync"
    "time"
    //"github.com/remeh/sizedwaitgroup"
)

// Taken from https://deviceatlas.com/blog/list-of-user-agent-strings
var (
    useragentstrings = map[string]string{
        "googleBot": "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
        "bingBot":   "Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)",
        "yahooBot":  "Mozilla/5.0 (compatible; Yahoo! Slurp; http://help.yahoo.com/help/us/ysearch/slurp)",
    }
    chromePath = "/root/tools/chromium-latest-linux/latest/chrome"
)

func fetchUsingChrome(url string, nameOfAgent string, useragent string, ch chan<- string, wg *sync.WaitGroup) {
    // func fetchUsingChrome(url string, nameOfAgent string, useragent string, ch chan<- string, wg *sizedwaitgroup.SizedWaitGroup) {
    start := time.Now()
    defer wg.Done()
    var chromeArguments = []string{
        "--headless", "--disable-gpu", "--hide-scrollbars", "--mute-audio", "--disable-notifications",
        "--disable-crash-reporter",
        "--ignore-certificate-errors",
        "--dump-dom",
        // "--screenshot=" + url + ".png",
        "--user-agent=" + useragent,
    }
    if os.Geteuid() == 0 {
        chromeArguments = append(chromeArguments, "--no-sandbox")
    }
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()

    cmd := exec.CommandContext(ctx, chromePath, chromeArguments...)
    stdout, _ := cmd.StdoutPipe()
    if err := cmd.Start(); err != nil {
        fmt.Printf("[%s]Dumping dom failed Error: %v\n", err)
        return
    }
    // buf := new(bytes.Buffer)

    // if err := buf.ReadFrom(stdout); err != nil {
    // fmt.Println(err)
    // return
    // }
    // fmt.Println(buf.String())
    if _, err := io.Copy(os.Stdout, stdout); err != nil {
        log.Fatal(err)
    }

    if err := cmd.Wait(); err != nil {
        if ctx.Err() == context.DeadlineExceeded {
            fmt.Printf("Dumping dom timed out : %s\n", url)
            return
        }
        fmt.Printf("[%s]Dumping dom failed Error: %v\n", err)
        return
    }
    secs := time.Since(start).Seconds()
    fmt.Println("Checking ", nameOfAgent)
    ch <- fmt.Sprintf("%.2f URL : %s", secs, url)
}

func main() {
    var wg sync.WaitGroup
    output := []string{
        "https://www.facebook.com",
        "https://www.google.com",
    }
    start := time.Now()
    ch := make(chan string)
    //swg := sizedwaitgroup.New(10)
    for _, url := range output {
        for k, v := range useragentstrings {
            wg.Add(1)
            //swg.Add()
            go fetchUsingChrome(url, k, v, ch, &wg)
            // go fetchUsingChrome(url, k, v, ch, &swg)
        }
    }

    go func() {
        wg.Wait()
        // swg.Wait()
        close(ch)
    }()
    for val := range ch {
        fmt.Println(val)
    }
    fmt.Printf("Total time taken %.2fs elapsed\n", time.Since(start).Seconds())
}

P.S.:我特意留下了一些注释代码,以便了解我尝试过的所有内容和失败的内容。

谢谢
临时工
(一个golang noobie)

【问题讨论】:

  • 为什么不增加超时时间?如果您并行执行更多工作,则可能需要更长的时间。或者只是不做那么多并行工作。
  • @Volker 感谢您的建议,但我想指出超时与 aquatone 中的相同,那么为什么要“超时”呢?

标签: go google-chrome-headless


【解决方案1】:

我建议启动 chrome headless,然后使用 Chrome DevTools Protocol 来控制您在本地计算机上打开的实例,但它也适用于远程 chrome 实例。

你可以使用这个库:https://github.com/chromedp/chromedp

我用它来截取我在 docker 容器中打开的 Chrome 无头网页。

这是我所做的一个小例子:https://gist.github.com/efimovalex/9f9b815b0d5b1b7889a51d46860faf8a

【讨论】:

  • 感谢您的回答,但正如您在 issue 128 中看到的那样,它仍然无法做到这一点,即使我已经在那里提出了答案,但这在多线程 goroutine 中不起作用。然而,aquatone 做到了,所以我试图在我的代码中复制该功能。
猜你喜欢
  • 2018-01-19
  • 1970-01-01
  • 2020-01-20
  • 1970-01-01
  • 2018-03-16
  • 1970-01-01
  • 2019-05-08
  • 1970-01-01
  • 2019-03-17
相关资源
最近更新 更多