【问题标题】:Read a local HTML file with Mechanize使用 Mechanize 读取本地 HTML 文件
【发布时间】:2011-11-27 01:10:06
【问题描述】:

我正在构建一个爬虫,我知道如何使用 ruby​​ mechanize 使用以下代码从网上读取页面:

require 'mechanize'
agent = Mechanize.new
agent.get "http://google.com"

但是我可以使用 Mechanize 从文件系统中读取 HTML 文件吗?怎么样?

【问题讨论】:

    标签: ruby mechanize


    【解决方案1】:

    基于@Stephens 的回答;由于fakeweb 的更新时间较长且维护者的情况尚不清楚,因此这里有一个使用webmock 解决此问题的答案,对于赶时间的人来说:

    require 'webmock'
    include WebMock::API
    
    WebMock.enable!
    stub_request(:get, "www.example.com").to_return(body: File.read("page.html"))
    
    agent = Mechanize.New
    page = agent.get("http://www.example.com/")
    
    # ...
    

    【讨论】:

      【解决方案2】:

      我无法让file:// 协议为我正常工作。相反,我通过在本地保存网页并注册 URI 来使用 Fakeweb

      stream = File.read("saved_google_page.html")
      FakeWeb.register_uri(:get, "http://www.google.com", :body => stream, :content_type => "text/html")
      

      并让 Fakeweb 使用正常的机械化过程在幕后返回它

      agent = Mechanize.New
      page = agent.get("http://www.google.com/")
      

      How to test a ruby application which uses mechanize

      【讨论】:

      • 不错的工具,我也很难使用file:// - 现在的问题是:为什么?!
      【解决方案3】:

      恕我直言,在这种情况下尝试使用机械化是没有意义的。也许您想解析 HTML。然后试试nokogiri(mechanize 也用它来解析)

      例如使用

      Nokogiri::HTML(open('index.html'))
      

      而不是

      session.get('http://www.google.com')
      

      【讨论】:

      • 感谢您的快速回复,我完全理解使用 nokogiri 的好处,实际上 mechanize 也使用它,但是有些方法已经内置在 mechanize 中,没有任何额外的 nokogiri 编码......所以我希望看看能不能做到?
      • 我不明白您希望如何与静态 HTML 文件进行交互。也许如果您更新问题,我们可以提供进一步的帮助
      • 好的,我又看了一下 nokogiri,我认为它涵盖了我现在需要的所有内容,谢谢!
      【解决方案4】:

      仅使用 file:// 协议对我来说效果很好:

      html_dir = File.dirname(__FILE__)
      page = agent.get("file:///#{html_dir}/example-file.html")
      

      以及关于为什么有人会使用 mechanize 来读取本地 html 文件的问题:我发现它对于测试目的是必要的 - 只需在本地存储一个示例文件并针对它运行您的 rspec。

      【讨论】:

      • 使用 File.dirname(__FILE__) 给了我 404 错误。但对我有用的是这样做:page = agent.get("file:///#{Dir.pwd}/example-file.html")
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 2018-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多