我正在寻找有关循环浏览网站上连续页面的最佳方式的帮助,同时从每个页面上抓取相关数据。
例如,我想访问特定站点(以下示例中的 craigslist),从第一页抓取数据,转到下一页,抓取所有相关数据等,直到最后一页。
在我的脚本中,我使用了 while
循环,因为它对我来说似乎最有意义。但是,它似乎无法正常工作,只是从第一页抓取数据。
熟悉 Ruby/Mechanize 的人能否为我指明完成此任务的最佳方法的正确方向。我花了无数个小时试图弄清楚这一点,但我觉得我错过了一些非常基本的东西。
在此先感谢您的帮助。
require 'mechanize'
require 'pry'
# initialze
agent = Mechanize.new { |agent| agent.user_agent_alias = 'Mac Safari'}
url = "http://charlotte.craigslist.org/search/rea"
page = agent.get(url)
# Create an empty array to dump contents into
property_results = []
# Scrape all successive pages from craigslist
while page.link_with(:dom_class => "button next") != nil
next_link = page.link_with(:dom_class => "button next")
page.css('ul.rows').map do |d|
property_hash = { title: d.at_css('a.result-title.hdrlnk').text }
property_results.push(property_hash)
end
page = next_link.click
end
更新:
我找到了这个,但仍然没有骰子:
Ruby Mechanize: Follow a Link
@pguardiario
require 'mechanize'
require 'httparty'
require 'pry'
# initialze
agent = Mechanize.new
url = "http://charlotte.craigslist.org/search/rea"
page = agent.get(url)
#create Empty Array
property_results = []
# Scrape all successive pages from craigslist
while link = page.at('[rel=next]')
page.css('ul.rows').map do |d|
property_hash = { title: d.at_css('a.result-title.hdrlnk').text }
property_results.push(property_hash)
end
link = page.at('[rel=next]')
page = agent.get link[:href]
end
pry(binding)
最佳答案
每当您看到 [rel=next]
,这就是您要遵循的内容:
page = agent.get url
do_something_with page
while link = page.at('[rel=next]')
page = agent.get link[:href]
do_something_with page
end
关于ruby - 使用 Ruby Mechanize 抓取所有连续的页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40880921/