php小編草莓,你好!關于你提到的問題,chromedp click 在你的 golang 代碼中無法起作用的情況,我可以幫你找出問題所在。chromedp 是一個使用 Chrome DevTools Protocol 進行自動化的庫,click 方法用于模擬鼠標點擊事件。可能的問題有:1. 頁面元素不可見或被其他元素遮擋,導致 click 失效;2. click 方法的參數傳遞有誤;3. chromedp 的版本與 Chrome 瀏覽器版本不兼容;4. 其他代碼邏輯問題。請提供更多細節,我將盡快給出解決方案。
問題內容
我正在使用 chromedp 開發 scrapper。
要獲得我想要的內容(頁面 html),我必須單擊特定按鈕。
所以我使用了 chromedp.click 和 chromedp.outerhtml,但我只得到了點擊前頁面的 html,而不是點擊完成后頁面的 html。
你能看到我的代碼并建議我如何修復它嗎?
func runCrawler(URL string, lineNum string, stationNm string) {
// settings for crawling
opts := append(chromedp.DefaultExecAllocatorOptions[:],
chromedp.Flag("headless", false))
// create chrome instance
contextVar, cancelFunc := chromedp.NewExecAllocator(context.Background(), opts...)
defer cancelFunc()
contextVar, cancelFunc = chromedp.NewContext(contextVar)
defer cancelFunc()
var htmlContent string
err := chromedp.Run(contextVar,
chromedp.Navigate(URL),
chromedp.WaitVisible(".end_footer_area"),
chromedp.Click(".end_section.station_info_section > div.at_end.sofzqce > div > div.c10jv2ep.wrap_btn_schedule.schedule_time > button"),
chromedp.OuterHTML("html", &htmlContent, chromedp.ByQuery),
)
fmt.Println("html", htmlContent)
checkErr(err)
登錄后復制
我還給你主頁和我需要點擊的按鈕
頁面網址:https://pts.map.naver.com/end-subway/ends/web/11321/home
我需要點擊的按鈕區域:
非常感謝
解決方法
您想要獲取的頁面已在新選項卡(目標)中打開。
在這種情況下,我們可以使用 chromedp.waitnewtarget 來創建一個 chan,從中我們可以接收新選項卡的目標 id。然后使用 chromedp.withtargetid 選項創建一個新上下文,以便我們可以連接到新選項卡。從這里開始,一切都是您已經熟悉的。
package main
import (
"context"
"fmt"
"strings"
"github.com/chromedp/cdproto/target"
"github.com/chromedp/chromedp"
)
func main() {
opts := append(chromedp.DefaultExecAllocatorOptions[:],
chromedp.Flag("headless", false),
)
ctx, cancel := chromedp.NewExecAllocator(context.Background(), opts...)
defer cancel()
ctx, cancel = chromedp.NewContext(ctx)
defer cancel()
var htmlContent string
ch := chromedp.WaitNewTarget(ctx, func(i *target.Info) bool {
return strings.Contains(i.URL, "/timetable/web/")
})
err := chromedp.Run(ctx,
chromedp.Navigate("https://pts.map.naver.com/end-subway/ends/web/11321/home"),
chromedp.WaitVisible(".end_footer_area"),
chromedp.Click(".end_section.station_info_section > div.at_end.sofzqce > div > div.c10jv2ep.wrap_btn_schedule.schedule_time > button"),
)
if err != nil {
panic(err)
}
newCtx, cancel := chromedp.NewContext(ctx, chromedp.WithTargetID(<-ch))
defer cancel()
if err := chromedp.Run(newCtx,
chromedp.WaitReady(".table_schedule", chromedp.ByQuery),
chromedp.OuterHTML("html", &htmlContent, chromedp.ByQuery),
); err != nil {
panic(err)
}
fmt.Println("html", htmlContent)
}
登錄后復制






