[英]Mechanize with FakeWeb
我正在使用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类现在是Page
puts page.class # => Page
那么,如何使用带有机械化功能的fakeweb返回Page而不是File对象呢?
使用FakeWeb重放预取的HTTP请求:
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将在响应中包含标头。
您可以轻松地解决该问题:content_type => "text/html"
在您的FakeWeb.register_uri
调用中添加选项:content_type => "text/html"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.