Golang 模拟浏览器操作:使用 chromedp 框架实现数据录入与请求
以下是使用 Golang 模拟打开浏览器并录入数据后请求的示例代码,使用了第三方框架 chromedp:
package main
import (
"context"
"fmt"
"time"
"github.com/chromedp/chromedp"
)
func main() {
// 定义要打开的页面URL和要输入的数据
url := 'https://www.example.com'
input := 'hello world'
// 创建一个上下文
ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()
// 打开页面
err := chromedp.Run(ctx, chromedp.Navigate(url))
if err != nil {
fmt.Printf("Error navigating to %s: %s\n", url, err)
return
}
// 等待页面加载
err = chromedp.Run(ctx, chromedp.Sleep(2*time.Second))
if err != nil {
fmt.Printf("Error waiting for page to load: %s\n", err)
return
}
// 输入数据
err = chromedp.Run(ctx, chromedp.SendKeys("#input-element", input))
if err != nil {
fmt.Printf("Error sending keys to input element: %s\n", err)
return
}
// 点击提交按钮
err = chromedp.Run(ctx, chromedp.Click("#submit-button"))
if err != nil {
fmt.Printf("Error clicking submit button: %s\n", err)
return
}
// 等待页面加载
err = chromedp.Run(ctx, chromedp.Sleep(2*time.Second))
if err != nil {
fmt.Printf("Error waiting for page to load: %s\n", err)
return
}
// 获取提交后的页面内容
var res string
err = chromedp.Run(ctx, chromedp.OuterHTML("#result-element", &res))
if err != nil {
fmt.Printf("Error getting result element HTML: %s\n", err)
return
}
fmt.Println(res)
}
该示例代码使用 chromedp 模拟打开一个网页,输入数据并点击提交按钮,然后获取提交后的页面内容。你可以根据自己的需求修改该示例代码来实现各种功能。
原文地址: https://www.cveoy.top/t/topic/nbL7 著作权归作者所有。请勿转载和采集!