2010-10-18 32 views
2

我有一个半小时前曾经工作过的小爬行器/屏幕抓取脚本,但现在它不再工作了。我检查了页面源代码中reg表达式的html和css值,但它们仍然是相同的,所以从这个角度来看,它应该起作用。任何猜测?红宝石屏幕抓取脚本中的问题

require "open-uri" 

# output file 
f = open 'results.csv', 'w+' 

# output string 
results = "" 

begin 

    # crawl first 20 pages 
    for i in (1..20) 
    open("http://www.example-#{i}.com") {|url| 

     # check each line using regular expression 
     url.each_line { |line| 
     if line =~ /class=\"L1g\" onclick=\"s_objectID=\'foobar\'\">([^<]+)<\/a><\/h3><\/li>/ 
      # if regular expression matches then add to results 
      results += $1 + "\n" 
     end 
     } 
    } 
    end 
ensure 
    # write to and close file 
    f.print results 
    f.close 
end 
+0

你说它不起作用,会发生什么? – mikej 2010-10-18 06:57:06

+0

用于打破Stack Overflow的语法高亮显示。它产生了什么异常消息?另外,你有没有尝试过[如何调试ruby脚本?]中提到的任何调试方法(http://stackoverflow.com/questions/3955688/how-do-i-debug-ruby-scripts) – 2010-10-18 06:57:52

+0

因此,页面是与往常一样,并且它在过去有效。你升级了Ruby吗? – Sirupsen 2010-10-18 08:48:57

回答

0

目标网站似乎已经改变了他们页面的结构,所以你的正则表达式不再匹配。

这是一个很好的例子,为什么你不应该使用正则表达式来匹配内容。尝试使用像Nokogiri这样的DOM解析器重新编写脚本。这不一定会阻止你的脚本破坏,但至少可以让它在较小的变化中幸存下来。

它不工作的原因可以在此Rubular链接

+0

必须的HTML和正则表达式链接:[RegEx匹配除XHTML自包含标记以外的开放标记](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained - 标签) – 2010-10-18 22:26:09

+0

感谢您的答案!将尝试修复与Nokogiri ... – hebe 2010-10-20 11:26:39

+0

@Andre格林:正则表达式链接是真棒... – hebe 2010-10-20 11:30:34

0

可见的网页抓取另一种选择是iMacros的。这些脚本很容易适应网站的变化。