首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用chromedp获取HTTP响应体?

如何使用chromedp获取HTTP响应体?
EN

Stack Overflow用户
提问于 2017-08-22 04:13:03
回答 1查看 6K关注 0票数 5

使用github.com/knq/chromedp (一个使用Chrome调试协议驱动web浏览器的go包),我可以导航到网页、更新表单和提交表单,但我需要检索一个HTTP主体,并且还没有找到如何。我希望能够检索JSON响应(而不是HTML)的HTTP响应主体。

从代码中可以看出,HTTP主体似乎位于CachedResponse.Body属性中:

https://github.com/knq/chromedp/blob/b9e4c14157325be092c1c1137edbd584648d8c72/cdp/cachestorage/types.go#L30

并且应该使用以下方法来访问:

代码语言:javascript
复制
func (p *RequestCachedResponseParams) Do(ctxt context.Context, h cdp.Handler) (response *CachedResponse, err error)

https://github.com/knq/chromedp/blob/b9e4c14157325be092c1c1137edbd584648d8c72/cdp/cachestorage/cachestorage.go#L168

这些示例使用cdp.Tasks,如简单示例中的如下所示。

代码语言:javascript
复制
func googleSearch(q, text string, site, res *string) cdp.Tasks {
    var buf []byte
    sel := fmt.Sprintf(`//a[text()[contains(., '%s')]]`, text)
    return cdp.Tasks{
        cdp.Navigate(`https://www.google.com`),
        cdp.Sleep(2 * time.Second),
        cdp.WaitVisible(`#hplogo`, cdp.ByID),
        cdp.SendKeys(`#lst-ib`, q+"\n", cdp.ByID),
        cdp.WaitVisible(`#res`, cdp.ByID),
        cdp.Text(sel, res),
        cdp.Click(sel),
        cdp.Sleep(2 * time.Second),
        cdp.WaitVisible(`#footer`, cdp.ByQuery),
        cdp.WaitNotVisible(`div.v-middle > div.la-ball-clip-rotate`, cdp.ByQuery),
        cdp.Location(site),
        cdp.Screenshot(`#testimonials`, &buf, cdp.ByID),
        cdp.ActionFunc(func(context.Context, cdptypes.Handler) error {
            return ioutil.WriteFile("testimonials.png", buf, 0644)
        }),
    }
}

https://github.com/knq/chromedp/blob/b9e4c14157325be092c1c1137edbd584648d8c72/examples/simple/main.go

似乎可以通过引用CachedResponse.Body来调用RequestCachedResponseParams.Do()来访问RequestCachedResponseParams.CacheID,但仍然需要以下内容:

  1. 如何在RequestCachedResponseParams.Do()中调用cdp.Tasks --似乎可以使用cdp.ActionFunc()
  2. 如何访问RequestCachedResponseParams.CacheID
EN

回答 1

Stack Overflow用户

发布于 2019-06-14 17:28:04

如果您想得到请求响应,我就是这样做的。

此示例调用http://www.google.com并侦听EventResponseReceived以保持包含标头的响应。

代码语言:javascript
复制
package main

import (
    "context"
    "io/ioutil"
    "log"
    "os"
    "time"

    "github.com/chromedp/cdproto/network"
    "github.com/chromedp/chromedp"
)

func main() {
    dir, err := ioutil.TempDir("", "chromedp-example")
    if err != nil {
        panic(err)
    }
    defer os.RemoveAll(dir)

    opts := append(chromedp.DefaultExecAllocatorOptions[:],
        chromedp.DisableGPU,
        chromedp.NoDefaultBrowserCheck,
        chromedp.Flag("headless", false),
        chromedp.Flag("ignore-certificate-errors", true),
        chromedp.Flag("window-size", "50,400"),
        chromedp.UserDataDir(dir),
    )

    allocCtx, cancel := chromedp.NewExecAllocator(context.Background(), opts...)
    defer cancel()

    // also set up a custom logger
    taskCtx, cancel := chromedp.NewContext(allocCtx, chromedp.WithLogf(log.Printf))
    defer cancel()

    // create a timeout
    taskCtx, cancel = context.WithTimeout(taskCtx, 10*time.Second)
    defer cancel()

    // ensure that the browser process is started
    if err := chromedp.Run(taskCtx); err != nil {
        panic(err)
    }

    // listen network event
    listenForNetworkEvent(taskCtx)

    chromedp.Run(taskCtx,
        network.Enable(),
        chromedp.Navigate(`http://www.google.com`),
        chromedp.WaitVisible(`body`, chromedp.BySearch),
    )

}

func listenForNetworkEvent(ctx context.Context) {
    chromedp.ListenTarget(ctx, func(ev interface{}) {
        switch ev := ev.(type) {

        case *network.EventResponseReceived:
            resp := ev.Response
            if len(resp.Headers) != 0 {
                log.Printf("received headers: %s", resp.Headers)

            }

        }
        // other needed network Event
    })
}
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45808799

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档