使用 Rod 库进行网页自动化操作:一个简单的爬虫示例
以下代码展示了如何使用 Rod 库进行网页自动化操作,并构建一个简单的爬虫,用于访问百度搜索并获取搜索结果。
l := launcher.New().
Headless(false).
Devtools(false)
defer l.Cleanup() // remove launcher.FlagUserDataDir
url := l.MustLaunch()
// Trace shows verbose debug information for each action executed
// SlowMotion is a debug related function that waits 2 seconds between
// each action, making it easier to inspect what your code is doing.
browser := rod.New().
ControlURL(url).
Trace(true).
SlowMotion(2 * time.Second).
MustConnect()
// ServeMonitor plays screenshots of each tab. This feature is extremely
// useful when debugging with headless mode.
// You can also enable it with flag '-rod=monitor'
launcher.Open(browser.ServeMonitor(''))
// Create a new page
page := browser.MustPage('https://www.baidu.com')
// We use css selector to get the search input element and input 'git'
page.MustElement('input').MustInput('git').MustType(input.Enter)
// Wait until css selector get the element then get the text content of it.
text := page.MustElement('.codesearch-results p').MustText()
fmt.Println(text)
// Get all input elements. Rod supports query elements by css selector, xpath, and regex.
// For more detailed usage, check the query_test.go file.
fmt.Println('Found', len(page.MustElements('input')), 'input elements')
// Eval js on the page
page.MustEval(`() => console.log('hello world')`)
// Pass parameters as json objects to the js function. This MustEval will result 3
fmt.Println('1 + 2 =', page.MustEval(`(a, b) => a + b`, 1, 2).Int())
// When eval on an element, 'this' in the js is the current DOM element.
fmt.Println(page.MustElement('title').MustEval(`() => this.innerText`).String())
defer browser.MustClose()
代码解释:
-
导入必要的库: 首先导入 Rod 库和 fmt 库,用于网页自动化操作和输出结果。
-
创建浏览器实例: 使用
launcher.New()创建一个浏览器实例,并设置Headless和Devtools属性。Headless属性控制浏览器是否以无头模式运行,Devtools属性控制是否开启开发者工具。 -
启动浏览器: 使用
l.MustLaunch()启动浏览器并获取控制 URL。 -
连接浏览器: 使用
rod.New().ControlURL(url).MustConnect()连接到浏览器。 -
打开页面: 使用
browser.MustPage('https://www.baidu.com')打开百度搜索页面。 -
输入搜索词: 使用
page.MustElement('input').MustInput('git').MustType(input.Enter)找到搜索输入框,输入搜索词 'git' 并回车。 -
获取搜索结果: 使用
page.MustElement('.codesearch-results p').MustText()获取搜索结果页面的文本内容。 -
获取所有输入框: 使用
page.MustElements('input')获取页面中所有输入框元素。 -
执行 JavaScript 代码: 使用
page.MustEval()执行 JavaScript 代码,包括输出 'hello world' 和计算 1 + 2 的结果。 -
获取元素的文本内容: 使用
page.MustElement('title').MustEval()获取页面标题元素的文本内容。 -
关闭浏览器: 使用
browser.MustClose()关闭浏览器实例。
注意:
- 本示例代码仅用于演示 Rod 库的基本用法,并不能用于实际的爬虫应用。
- 使用爬虫工具需要遵守目标网站的 robots.txt 文件和相关法律法规。
- 建议使用 Rod 库进行自动化测试或其他合法目的。
安装 Rod 库:
使用以下命令安装 Rod 库:
go get github.com/go-rod/rod
原文地址: https://www.cveoy.top/t/topic/odGg 著作权归作者所有。请勿转载和采集!