如何避免与 Mechanize 的间隔

How avoid interval with Mechanize

我正在尝试使用 Mechanize 抓取 Craiglist。我这样编码:

require 'mechanize'

a = Mechanize.new
page = a.get("http://paris.craigslist.fr/search/apa")
i = 0
list_per_page = 99
while i <= list_per_page do
    title = page.search(".hdrlnk")[i].text
    price = page.search(".price")[i].text
    puts title
    puts price
    puts "-----------"
    i+=1
end

它有效,但当列表没有任何价格时,会有一个间隔。我认为这是因为我使用 search()[i] 但我不知道我必须做什么才能避免间隔。有什么想法吗?

编辑:
在 Craiglist 上有:

listing_title1 -> 0
listing_title2 -> 0
listing_title3 -> 
listing_title4 -> 
listing_title5 -> 0

我的输出 CSV 显示:

listing_title1 -> 0
listing_title2 -> 0
listing_title3 -> 
listing_title4 -> 0
listing_title5 -> 0

300 美元是 listing_title6

如果 'interval' 你的意思是当列表没有价格时打印的空白行,你可以通过使 puts 有条件来解决这个问题:

puts price unless price.empty?

编辑

如果我没理解错的话,您的 hdrlnkprice 条目彼此不同步。发生这种情况是因为您当前的循环正在跳过带有空白 price 字段的条目并直接进入下一个。

解决这个问题的最佳方法是找到一个包含 pricehdrlnk 的容器,然后迭代这些容器而不是 hdrlnkprice条目分开。在此页面上,.row 包含每个搜索结果的所有信息。所以这样的事情会起作用:

page.search(".row").each do |row|
  title = row.search(".hdrlnk").first
  price = row.search(".price").first
  puts title.text if title
  puts price.text if price
  puts "------------"
end

我知道你已经接受了一个答案,这很好,但我想介绍 next 的概念,这是比遍历 if <thing> 检查更强大的解决方案。

您的方法可能如下所示:

while <condition> do
  title = page.search(".hdrlnk")[i].text
  price = page.search(".price")[i].text

  # skip to the next iteration if any of the vars are nil
  next unless [title, price].all?

  # ... the rest of code
end

顺便说一下,我认为您对术语 'interval' 的使用有点误导。我认为间隔是一种特殊的循环,它在指定的 time 间隔上运行,即每秒或每分钟。在这种情况下使用术语 loopiteration 可能更清楚。