tasks:=chromedp.Tasks{
chromedp.Navigate("https://xxx/login"),
//等待加载出来的组件
chromedp.WaitVisible(usernameSel),
//用户输入框
chromedp.Click(usernameSel),
chromedp.SendKeys(usernameSel, user.Username),
//下一步
chromedp.Click(nextSel),
//用户密码输入框
chromedp.WaitVisible(pwSel),
chromedp.Click(pwSel),
chromedp.SendKeys(pwSel, user.Password),
//登录
chromedp.Click(loginSel),
//搜索框
chromedp.WaitVisible(SearchSel),
chromedp.Sleep(time.Second * 2),
chromedp.SendKeys(SearchSel, query+kb.Enter),
//等待文章内容出现
chromedp.WaitVisible(articleSel),
chromedp.Sleep(time.Second * 5),
//记录
chromedp.OuterHTML(`document.querySelector("body")`, &res[0], chromedp.ByJSPath),
chromedp.Sleep(time.Second * 3),
chromedp.ActionFunc(func(ctx context.Context) error {
for i := 1; i < maxPage; i++ {
//超过可以保存的范围直接跳出
if i >= fromPage+len(res) {
break
}
//翻页
err := chromedp.KeyEvent(kb.End).Do(ctx)
if err != nil {
return err
}
err = chromedp.Sleep(3 * time.Second).Do(ctx)
if err != nil {
return err
}
//保存在范围内的数据
if i >= fromPage && i < fromPage+len(res) {
//记录页面body里的内容
err = chromedp.OuterHTML(`document.querySelector("body")`, &res[i-fromPage], chromedp.ByJSPath).Do(ctx)
if err != nil {
return err
}
doc, err := goquery.NewDocumentFromReader(strings.NewReader(res[i-fromPage]))
if err != nil {
return err
}
//已到尾部不需要再翻页,跳出循环
if _, ok := doc.Find(endSel).Attr("class"); ok {
break
}
}
}
return nil
}),
}
调用:
//调用,初始化chromedp
options := []chromedp.ExecAllocatorOption{
chromedp.Flag("headless", true), //调试时false 设置成无浏览器弹出模式,出错中断可能会导致后台不能退出
chromedp.Flag("blink-settings", "imageEnable=false"),
chromedp.Flag("accept-language", `zh-CN,zh;`),
chromedp.ProxyServer(this.Proxy),
chromedp.UserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36"),
}
c, _ := chromedp.NewExecAllocator(context.Background(), options...)
chromeCtx, cancel := chromedp.NewContext(c, chromedp.WithLogf(log.Printf))
timeOutCtx, cancel := context.WithTimeout(chromeCtx, time.Minute*4+time.Second*15*time.Duration(from+1)) //翻页越多需要的时间就越多,分页每多一页多给15秒
defer cancel()
chromedp.Run(timeOutCtx, tasks)
使用goquery筛选出需要的内容:
github.com/PuerkitoBio/goquery
查找太深容易出现找不到的问题,可提取出特性来进行查找:
关于写法的3个举例:
div.css-1dbjc4n.r-o52ifk > div.css-1dbjc4n.r-o52ifk
#info > span.style-scope.yt-formatted-string.bold
第一个代码块密码框中的pwSel就等于`input[name=password]`