[Golang] 纯文本查看 复制代码
package common
import (
"context"
"github.com/chromedp/cdproto/cdp"
"github.com/chromedp/chromedp"
"log"
"time"
)
func GetHttpHtmlContent(url string, visibleEleId string, clickEle bool, headless bool) (string, error) {
opts := append(chromedp.DefaultExecAllocatorOptions[:],
chromedp.Flag("headless", headless),
)
c, concel_at_begin := chromedp.NewExecAllocator(context.Background(), opts...) # 这里的变量concel_at_begin 一定不能省去
// create context
chromeCtx, cancel := chromedp.NewContext(c, chromedp.WithLogf(log.Printf))
// Execute an empty task, Create in advance with Chrome example
chromedp.Run(chromeCtx, make([]chromedp.Action, 0, 1)...)
// Create a context , The timeout is 40s
timeoutCtx, cancel := context.WithTimeout(chromeCtx, 20*time.Second)
defer cancel()
var htmlContent string
var res []*cdp.Node
chromedp.Run(chromeCtx,
chromedp.Navigate(url),
//chromedp.EvaluateAsDevTools(fmt.Sprintf(`document.querySelector("%v")`, visibleEleId), ""),
chromedp.Nodes(visibleEleId, &res, chromedp.AtLeast(0)),
)
if len(res) != 0 {
//fmt.Println("length res is not 0, find the element", res)
if clickEle {
chromedp.Run(timeoutCtx,
chromedp.SendKeys(`select[id=selectT]`, "终"),
chromedp.Sleep(30*time.Second),
chromedp.OuterHTML(`body`, &htmlContent, chromedp.ByQuery),
)
} else {
chromedp.Run(timeoutCtx,
chromedp.OuterHTML(`body`, &htmlContent, chromedp.ByQuery),
)
}
} else {
//fmt.Println("length res is 0, not find the element")
chromedp.Run(timeoutCtx,
chromedp.OuterHTML(`body`, &htmlContent, chromedp.ByQuery),
)
}
concel_at_begin() # 在这里添加这一句, 程序会在这里自动关闭浏览器
return htmlContent, nil
}