我试图打开chromedp库的结账页面,但它没有收到我发送的cookie。我在一个循环中尝试了network.SetCookies()
和network.SetCookie()
,但它不工作。* 编译运行无错误 *。感谢帮助,代码如下:
opts := append(chromedp.DefaultExecAllocatorOptions[:], chromedp.Flag("headless", false))
actx, cancel := chromedp.NewExecAllocator(context.Background(), opts...)
ctx, cancel := chromedp.NewContext(actx)
// Call cancel() to close Chrome on some condition.
if false {
cancel()
}
task := chromedp.Tasks{
network.Enable(),
chromedp.ActionFunc(func(ctx context.Context) error {
cookieJar := getCookies(client)
var cookiesParam []*network.CookieParam
for _, v := range cookieJar {
fmt.Println(v.Name, ":"+v.Value)
cookiesParam = append(cookiesParam, &network.CookieParam{Name: v.Name, Value: v.Value})
}
network.SetCookies(cookiesParam)
return nil
}),
chromedp.Navigate(res.Request.URL.String()),
}
// Run task.
err := chromedp.Run(ctx, task)
if err != nil {
log.Fatal(err)
}
字符串
编辑:我尝试了@zachyoung给出的例子,但是当我尝试发送任何类型的cookie时,它都不起作用。代码如下:
// Command cookie is a chromedp example demonstrating how to set a HTTP cookie
// on requests.
package main
import (
"context"
"log"
"time"
"github.com/chromedp/cdproto/cdp"
"github.com/chromedp/cdproto/network"
"github.com/chromedp/chromedp"
)
func main() {
// create context
ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()
// run task list
var res string
err := chromedp.Run(ctx, setcookies("https://en.afew-store.com/", &res,
"cookie1", "value1",
"cookie2", "value2",
))
if err != nil {
log.Fatal(err)
}
log.Printf("chrome received cookies: %s", res)
}
// setcookies returns a task to navigate to a host with the passed cookies set
// on the network request.
func setcookies(host string, res *string, cookies ...string) chromedp.Tasks {
if len(cookies)%2 != 0 {
panic("length of cookies must be divisible by 2")
}
return chromedp.Tasks{
chromedp.ActionFunc(func(ctx context.Context) error {
// create cookie expiration
expr := cdp.TimeSinceEpoch(time.Now().Add(180 * 24 * time.Hour))
// add cookies to chrome
for i := 0; i < len(cookies); i += 2 {
err := network.SetCookie(cookies[i], cookies[i+1]).
WithExpires(&expr).
WithDomain("https://en.afew-store.com/").
WithHTTPOnly(true).
Do(ctx)
if err != nil {
return err
}
}
return nil
}),
// navigate to site
chromedp.Navigate(host),
// read the returned values
chromedp.Text(`#result`, res, chromedp.ByID, chromedp.NodeVisible),
// read network values
chromedp.ActionFunc(func(ctx context.Context) error {
cookies, err := network.GetAllCookies().Do(ctx)
if err != nil {
return err
}
for i, cookie := range cookies {
log.Printf("chrome cookie %d: %+v", i, cookie)
}
return nil
}),
}
}
型
2条答案
按热度按时间qlvxas9a1#
https://en.afew-store.com/
不是一个域,您应该将其替换为en.afew-store.com
。字符串
页面上没有
#result
元素,所以chromedp.Text("#result", res, chromedp.ByID, chromedp.NodeVisible)
永远不会返回。下面是一个修改后的演示:型
u5rb5r592#
我遇到了同样的问题,我添加了URL。
您可以添加一个错误检查来查看发生了什么。
字符串