如何在Rails中使用Nokogiri从URL获取HTML正文?

时间:2014-01-20 06:08:17

标签: ruby-on-rails nokogiri

我想从URL解析body属性。

例如:

url = 'http://rca.yandex.com/?key=rca.1.1.20140120T051507Z.3db118ab435efdff.6c84331313b6b7d66abd191410f72e0e1c3c8795&url=http://endtimeheadlines.wordpress.com/2014/01/17/think-tank-extraordinary-crisis-needed-to-preserve-new-world-order/#comment-36708?utm_source=twitterfeed&utm_medium=facebook[&callback=http://64.191.99.245:3023/posts][&full=1]'

当我尝试:

page = Nokogiri::HTML(html)

我明白了:

#<Nokogiri::HTML::Document:0x52fd6d6 name="document" children=[#<Nokogiri::XML::DTD:0x52fd1f4 name="html">, #<Nokogiri::XML::Element:0x52fc6aa name="html" children=[#<Nokogiri::XML::Element:0x5301f56 name="body" children=[#<Nokogiri::XML::Element:0x53018d0 name="p" children=[#<Nokogiri::XML::Text:0x53015f6 "http://rca.yandex.com/?key=rca.1.1.20140120T051507Z.3db118ab435efdff.6c84331313b6b7d66abd191410f72e0e1c3c8795&url=http://endtimeheadlines.wordpress.com/2014/01/17/think-tank-extraordinary-crisis-needed-to-preserve-new-world-order/#comment-36708?utm_source=twitterfeed&utm_medium=facebook[&callback=http://64.191.99.245:3023/posts][&full=1]">]>]>]>]>

如何获取此网址中的属性?

例如:page.css("div")。我想从HTML body中获取值。

4 个答案:

答案 0 :(得分:19)

目前还不清楚你要做什么,但这可能会有所帮助:

require 'nokogiri'

html = '<html><head><title>foo</title><body><p>bar</p></body></html>'

doc = Nokogiri::HTML(html)

使用at,您会发现第一次出现的代码,这在HTML文档中是合理的,因为您应该只有一个<body>代码。

doc.at('body') # => #<Nokogiri::XML::Element:0x3ff194d24cd4 name="body" children=[#<Nokogiri::XML::Element:0x3ff194d24acc name="p" children=[#<Nokogiri::XML::Text:0x3ff194d248c4 "bar">]>]>

如果您想要标记的子项,请使用children检索它们:

doc.at('body').children # => [#<Nokogiri::XML::Element:0x3ff194d24acc name="p" children=[#<Nokogiri::XML::Text:0x3ff194d248c4 "bar">]>]

如果要将子节点作为HTML:

doc.at('body').children.to_html # => "<p>bar</p>"
doc.at('body').inner_html # => "<p>bar</p>"

如果您想要正文标记的文本内容:

doc.at('body').content # => "bar"
doc.at('body').text # => "bar"

如果,通过“属性”,您实际上是指<body>标记本身的attributes

require 'nokogiri'

html = '<html><head><title>foo</title><body on_load="do_something()"><p>bar</p></body></html>'

doc = Nokogiri::HTML(html)
doc.at('body').attributes # => {"on_load"=>#<Nokogiri::XML::Attr:0x3fdc3d923ca0 name="on_load" value="do_something()">}
doc.at('body')['on_load'] # => "do_something()"

attributes返回一个哈希值,因此您可以直接访问所需的任何内容。作为一种捷径,Nokogiri :: XML :: Node也理解[]给我们一个典型的Hash风格的访问权限。

答案 1 :(得分:2)

page.css('body')应该有效。如果没有尝试使用to_s

答案 2 :(得分:0)

您可以根据需要使用to_xmlto_html或其他格式。有关其他格式选项,请参阅Nokogiri文档。

page = Nokogiri::HTML(html)
page.to_xml

要获取divdocument的正文,请使用:

divs = page.css('div') # returns either string or array depending upon the number of divs in your document.
divs.to_xml

答案 3 :(得分:0)

当然,您将获得已从链接获取的已解析的 HTML / XML 树。就在你的例子中:

page.css("div")

你只是约会,将解析后的文档中的所有div作为Array。你可以逐个枚举它们,并得到每个div的文本:

page.css("div").each do| div |
   p div.text
end