【问题标题】:How to get the page source with Mechanize/Nokogiri如何使用 Mechanize/Nokogiri 获取页面源
【发布时间】:2011-06-26 22:20:08
【问题描述】:

我已使用 Mechanize 登录到网页/servlet。

我有一个页面对象:

jobShortListPg = agent.get(addressOfPage)

当我使用时:

puts jobShortListPg

我得到了我不想要的页面的“机械化”版本:

#<Mechanize::Page::Link "Home" "blahICScriptProgramName=WEBLIB_MENU.ISCRIPT3.FieldFormula.IScript_DrillDown&target=main0&Level=0&RL=&navc=3171">

如何获取页面的 HTML 源代码?

【问题讨论】:

  • 在 Ruby 中,我们使用snake_case,而不是camelCase 来表示变量或方法名。 ItIsAReadabilityThing。

标签: ruby nokogiri mechanize


【解决方案1】:

使用.body:

puts jobShortListPg.body

【讨论】:

  • 我仍然得到页面的机械化版本:(。
  • 你确定你在.get返回的页面上做了.body吗?我得到一个纯字符串。 Mechanize.new.get("http://www.google.com").body.class => String
  • 愚蠢的我,我正在处理错误的文件。在正确的文件上做了 .body 并且它起作用了!谢谢Dogbert!
  • 机械化版本比源码好。他们有很多帮手
  • @carbonr 除非调用 API 并且源是您实际需要的 JSON
【解决方案2】:

使用页面对象的content方法。

jobShortListPg.content

【讨论】:

    【解决方案3】:

    在 Nokogiri 中,在主文档节点上使用 to_sto_html

    require 'nokogiri'
    
    doc = Nokogiri::HTML(<<EOT)
    <html>
      <head></head>
      <body>foo</body>
    </html>
    EOT
    
    doc.to_html
    # => "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\">\n" +
    #    "<html>\n" +
    #    "  <head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"></head>\n" +
    #    "  <body>foo</body>\n" +
    #    "</html>\n"
    

    或:

    doc.to_s
    # => "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\">\n" +
    #    "<html>\n" +
    #    "  <head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"></head>\n" +
    #    "  <body>foo</body>\n" +
    #    "</html>\n"
    

    如果看到嵌入的换行符会分散您的注意力,这可能会有所帮助:

    puts doc.to_s
    
    # >> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
    # >> <html>
    # >>   <head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></head>
    # >>   <body>foo</body>
    # >> </html>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多