【问题标题】:is it possible to convert Mechanize::File into Mechanize::Page是否可以将 Mechanize::File 转换为 Mechanize::Page
【发布时间】:2012-06-11 06:57:10
【问题描述】:

我在使用 Mechanize gem 时遇到问题,如何将 Mechanize::File 转换为 Mechanize::Page

这是我的一段代码:

**link** = page.link_with(:href => %r{/en/users}).click

当用户点击链接时,它会转到带有用户列表的页面,现在我想点击第一个用户,但我无法做到这一点,因为 link 返回 Mechanize: :文件对象

任何帮助,建议都会很棒,谢谢

【问题讨论】:

  • 有谁知道如何处理这种情况?

标签: ruby gem mechanize mechanize-ruby


【解决方案1】:

Mechanize 使用 Content-Type 来确定应如何处理资源。有时网站不会为其资源设置 MIME 类型。 Mechanize::File 是未设置 Content-Type 的默认值。

如果您只与 'text/html' 打交道,您可以关注 Jimm Stout 的 suggestion 使用 post_connect_hooks

agent = Mechanize.new do |a|
  a.post_connect_hooks << ->(_,_,response,_) do
    if response.content_type.empty?
      response.content_type = 'text/html'
    end
  end
end

【讨论】:

    【解决方案2】:

    只需用 nokogiri 解析身体:

    link = page.link_with(:href => %r{/en/users}).click
    doc = Nokogiri::HTML link.body
    agent.get doc.at('a')[:href]
    

    【讨论】:

      猜你喜欢
      • 2012-05-26
      • 2012-02-10
      • 1970-01-01
      • 2013-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-26
      相关资源
      最近更新 更多