使用chromedp,从* runtime.RemoteObject中获取JavaScript对象/数组

时间:2019-03-08 12:29:53

标签: javascript google-chrome go web-scraping

我正在使用chromedp,我想获取我滚动的页面内声明的javascript数组的内容

<script>
                var title = document.title;
                var pages = [{"key1":"value1","key2":1,"external":1},{"key1":"value2", "key2":9}];
</script>

我尝试了

var res *runtime.RemoteObject
if err := c.Run(ctxt, chromedp.EvaluateAsDevTools("pages", &res)); err != nil {
    return fmt.Errorf("could not evaluate page : %v", err)
}

json_byte, _ := res.MarshalJSON()
var out bytes.Buffer
_ = json.Indent(&out, json_byte, "", "\t")

log.Printf("pages %s ", out.String())

但是它给了我类似

2019/03/08 13:12:52 pages {
        "type": "object",
        "subtype": "array",
        "className": "Array",
        "description": "Array(22)",
        "objectId": "{\"injectedScriptId\":441,\"id\":1}"
}

我希望能够获取可变页面(键和值)的实际内容。如何获得此内容?

1 个答案:

答案 0 :(得分:1)

Find out that adding the option/function chromedp.EvalAsValue to eval does it :

if err := c.Run(ctxt, chromedp.EvaluateAsDevTools("pages", &res, chromedp.EvalAsValue)); err != nil {
    return fmt.Errorf("could not evaluate page : %v", err)
}

The result is the value of the evaluation not a summary.