1

我正在使用 Mechanize 从页面中提取链接。为了简化开发,我使用 fakeweb 进行超快速响应,以减少每次运行代码时的等待和烦人。

tags_url = "http://website.com/tags/"
FakeWeb.register_uri(:get, tags_url, :body => "tags.txt")

agent = WWW::Mechanize.new
page = agent.get(tags_url)
page.links.each do |link|
   puts link.text.strip
end

当我运行上面的代码时,它说:

nokogiri_test.rb:33: undefined method `links' for #<WWW::Mechanize::File:0x9a886e0> (NoMethodError)

检查页面对象的类后

puts page.class # => File

如果我不伪造 tags_url,它可以工作,因为页面类现在是 Page

puts page.class # => Page

那么,如何使用带有 mechanize 的 fakeweb 来返回 Page 而不是 File 对象呢?

4

2 回答 2

7

使用 FakeWeb 重放预取的 H​​TTP 请求:

tags_url = "http://website.com/tags/"
request  = `curl -is #{tags_url}`
FakeWeb.register_uri(:get, tags_url, :response => request)

agent = WWW::Mechanize.new
page = agent.get(tags_url)
page.links.each do |link|
   puts link.text.strip
end

使用 -i 标志调用 curl 将在响应中包含标头。

于 2009-12-09T10:38:05.097 回答
5

您可以轻松地解决这个问题,添加:content_type => "text/html"FakeWeb.register_uri呼叫的选项

于 2011-06-19T17:50:30.010 回答