所以我试图使用ruby mechanize和hpricot提取我网站的电子邮件。 我试图在我的管理方面的所有页面上进行循环,并用hpricot解析页面。这么好。然后我得到:
Exception `Net::HTTPBadResponse' at /usr/lib/ruby/1.8/net/http.rb:2022 - wrong status line: *SOME HTML CODE HERE*
当它解析一堆页面时,它以超时开始,然后打印页面的html代码。 不明白为什么?我怎么调试呢? 看起来机械化可以连续超过10页?可能吗?? 感谢
require 'logger'
require 'rubygems'
require 'mechanize'
require 'hpricot'
require 'open-uri'
class Harvester
def initialize(page)
@page=page
@agent = WWW::Mechanize.new{|a| a.log = Logger.new("logs.log") }
@agent.keep_alive=false
@agent.read_timeout=15
end
def login
f = @agent.get( "http://****.com/admin/index.asp") .forms.first
f.set_fields(:username => "user", :password =>"pass")
f.submit
end
def harvest(s)
pageNumber=1
#@agent.read_timeout =
s.upto(@page) do |pagenb|
puts "*************************** page= #{pagenb}/#{@page}***************************************"
begin
#time=Time.now
#search=@agent.get( "http://****.com/admin/members.asp?action=search&term=&state_id=&r=500&p=#{page}")
extract(pagenb)
rescue => e
puts "unknown #{e.to_s}"
#puts "url:http://****.com/admin/members.asp?action=search&term=&state_id=&r=500&p=#{page}"
#sleep(2)
extract(pagenb)
rescue Net::HTTPBadResponse => e
puts "net exception"+ e.to_s
rescue WWW::Mechanize::ResponseCodeError => ex
puts "mechanize error: "+ex.response_code
rescue Timeout::Error => e
puts "timeout: "+e.to_s
end
end
end
def extract(page)
#puts search.body
search=@agent.get( "http://***.com/admin/members.asp?action=search&term=&state_id=&r=500&p=#{page}")
doc = Hpricot(search.body)
#remove titles
#~ doc.search("/html/body/div/table[2]/tr/td[2]/table[3]/tr[1]").remove
(doc/"/html/body/div/table[2]/tr/td[2]/table[3]//tr").each do |tr|
#delete the phone number from the html
temp = tr.search("/td[2]").inner_html
index = temp.index('<')
email = temp[0..index-1]
puts email
f=File.open("./emails", 'a')
f.puts(email)
f.close
end
end
end
puts "starting extacting emails ... "
start =ARGV[0].to_i
h=Harvester.new(186)
h.login
h.harvest(start)
答案 0 :(得分:3)
Mechanize将页面的完整内容放入历史记录中,这可能会在浏览多个页面时导致问题。要限制历史记录的大小,请尝试
@mech = WWW::Mechanize.new do |agent|
agent.history.max_size = 1
end