
Lucas Mitchell
Automation Engineer
网络抓取已成为开发人员必备技能,他们需要从网站收集数据。Playwright 是一款强大的浏览器自动化工具,常用于此目的。在本指南中,我们将探讨如何使用 Playwright 与 Ruby 从网站抓取数据。我们将使用 Quotes to Scrape 网站逐步完成一个实际示例。
在我们开始之前,请确保你的机器上已安装以下内容:
你可以通过运行以下命令来安装必要的依赖项:
gem install playwright-ruby-client
安装 playwright-ruby-client gem 后,你需要在 Ruby 脚本中设置 Playwright。以下是操作方法:
require 'playwright'
Playwright.create(playwright_cli_executable_path: '/path/to/node_modules/.bin/playwright') do |playwright|
browser = playwright.chromium.launch(headless: false)
page = browser.new_page
page.goto('http://quotes.toscrape.com/')
# 示例抓取代码将位于此处
browser.close
end
将 '/path/to/node_modules/.bin/playwright' 替换为系统中 Playwright CLI 的实际路径。
现在,让我们编写代码来从网站抓取引言。我们将提取每个引言的文本及其对应的作者。
require 'playwright'
Playwright.create(playwright_cli_executable_path: '/path/to/node_modules/.bin/playwright') do |playwright|
browser = playwright.chromium.launch(headless: false)
page = browser.new_page
page.goto('http://quotes.toscrape.com/')
quotes = page.query_selector_all('.quote')
quotes.each do |quote|
quote_text = quote.query_selector('.text').text_content.strip
author = quote.query_selector('.author').text_content.strip
puts "#{quote_text} - #{author}"
end
browser.close
end
本指南向您展示了如何在 Ruby 中设置 Playwright 以及如何从网站上抓取数据。这里使用的示例很简单,但可以扩展以完成更复杂的任务。Playwright 自动执行浏览器任务的能力使其成为网页抓取和测试的强大工具。
祝您抓取愉快!
通过我们面向开发人员的全面API文档,掌握验证码解决技巧。学习如何将CapSolver集成到您的系统中,以处理reCAPTCHA、AWS WAF以及更多内容。
