CAPSOLVER
博客
使用 Playwright 与 Ruby:2024 年逐步指南

使用 Playwright 与 Ruby:2024 年逐步指南

Logo of CapSolver

Lucas Mitchell

Automation Engineer

02-Sep-2024

使用 Playwright 与 Ruby:2024 年逐步指南

网络抓取已成为开发人员必备技能,他们需要从网站收集数据。Playwright 是一款强大的浏览器自动化工具,常用于此目的。在本指南中,我们将探讨如何使用 Playwright 与 Ruby 从网站抓取数据。我们将使用 Quotes to Scrape 网站逐步完成一个实际示例。

先决条件

在我们开始之前,请确保你的机器上已安装以下内容:

  • Ruby (版本 2.7 或更高版本)
  • Node.js (Playwright 需要 Node.js 才能运行)
  • Playwright Gem (Playwright 的 Ruby 包装器)

你可以通过运行以下命令来安装必要的依赖项:

bash 复制代码
gem install playwright-ruby-client

设置 Playwright

安装 playwright-ruby-client gem 后,你需要在 Ruby 脚本中设置 Playwright。以下是操作方法:

ruby 复制代码
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 的实际路径。

从网站抓取引言

现在,让我们编写代码来从网站抓取引言。我们将提取每个引言的文本及其对应的作者。

ruby 复制代码
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|
ruby 复制代码
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 自动执行浏览器任务的能力使其成为网页抓取和测试的强大工具。

祝您抓取愉快!

合规声明: 本博客提供的信息仅供参考。CapSolver 致力于遵守所有适用的法律和法规。严禁以非法、欺诈或滥用活动使用 CapSolver 网络,任何此类行为将受到调查。我们的验证码解决方案在确保 100% 合规的同时,帮助解决公共数据爬取过程中的验证码难题。我们鼓励负责任地使用我们的服务。如需更多信息,请访问我们的服务条款和隐私政策。

更多