Craigslist Command Line Search Using Ruby

Posted by Tully on Mon 02 December 2013

One of my friends keeps looking through apartments on Craigslist. I figured it would be easier to just do quick searches through the command line.

I built a simple Ruby command line script for searching apartments. It takes a single argument, the search query. I have hardcoded some values such as hasPic, maxAsk, minAsk, and a few others. If you want to use this, these can easily be changed by updating the scripts values.

require 'open-uri'
require 'mechanize'
require 'colorize'

unless ARGV[0]
    puts 'Usage: ./craigslist.rb <query>'
    exit
end

query = ARGV[0]
craigslist_url = 'http://losangeles.craigslist.org'

url = []
url << "http://losangeles.craigslist.org/search/sss"
url << "?catAbb=hhh"
url << "&query=#{query}"
url << "&zoomToPosting="
url << "&minAsk=800"
url << "&maxAsk=1400"
url << "&hasPic=1"
url = url.join

mech = Mechanize.new { |agent|
    agent.user_agent_alias = 'Mac Safari'
}

mech.get(url) do |page|
    page.search("//p[@class='row']").each do |row|
        link = row.search('a')[0]
        link_href = /^http/ =~ link['href'] ? link['href'] : craigslist_url + link['href']
        link_text = row.search('a')[1].text
        city = row.search("small").text
        price = row.search("span[@class='price']")[0].text

        puts "#{price.red} #{city} - #{link_text.blue}\n#{link_href.cyan}\n"
    end
end

Usage

./craigslist.rb LOCATION

Example

./craigslist.rb "santa monica"