thank_you
thank_you

Reputation: 11107

Screen scraping with Nokogiri and Each method returning zero

I'm running the following code:

require 'rubygems'
require 'nokogiri'
require 'open-uri'

url = "http://sfbay.craigslist.org/search/sss?query=bike&catAbb=sss&srchType=A&minAsk=&maxAsk="

doc = Nokogiri::HTML(open(url))
doc.css(".row").each do |row|
  row.css("a").text
end

The only thing I get returned is 0. However, when I just run doc.css(".row"), I get the entire list of rows from the CL. Why is it returning zero when I use the each method and how do I fix it?

Upvotes: 2

Views: 218

Answers (2)

Mark Thomas
Mark Thomas

Reputation: 37527

You don't need to issue two different css queries; you can combine them:

doc.css(".row > a").map(&:text)

Upvotes: 1

Zach Kemp
Zach Kemp

Reputation: 11904

.each doesn't return anything, it's a simple iterator. Perhaps you are looking for .map?

This will return an array of the anchor element text:

doc.css(".row").map {|row| row.css("a").text }

Upvotes: 2

Related Questions