使用 Nokogiri 的一些例子有哪些?
我试图理解Nokogiri。有谁有 Nokogiri 解析/抓取的基本示例的链接,显示生成的树。我认为这确实有助于我的理解。
I am trying to understand Nokogiri. Does anyone have a link to a basic example of Nokogiri parse/scrape showing the resultant tree. Think it would really help my understanding.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 IRB 和 Ruby 1.9.2:
加载 Nokogiri:
解析文档:
Nokogiri 喜欢格式良好的文档。请注意,它添加了
DOCTYPE
因为我解析为文档。也可以解析为文档片段,但这非常专业。使用 CSS 搜索文档以查找第一个
节点并获取其内容:
使用不同的方法名称执行相同的操作:
在文档中搜索所有
< /code> 节点位于
标签内,并获取第一个节点的内容。
search
返回一个节点集,它就像一个节点数组。这是很重要的一点,也是几乎每个人第一次使用 Nokogiri 时都会遇到的问题。
search
及其css
和xpath
变体返回一个 NodeSet。NodeSet.text
或content
将所有返回节点的文本连接到一个字符串中,这使得再次拆分变得非常困难。使用稍微不同的 HTML 有助于说明这一点:
返回到原始 HTML...
更改节点的内容:
将解析后的文档作为 HTML 发出:
删除节点:
至于抓取,有很多关于使用的问题Nokogiri 用于从网站中分离 HTML。在 StackOverflow 中搜索“nokogiri 和 open-uri”应该会有所帮助。
Using IRB and Ruby 1.9.2:
Load Nokogiri:
Parse a document:
Nokogiri likes well formed docs. Note that it added the
DOCTYPE
because I parsed as a document. It's possible to parse as a document fragment too, but that is pretty specialized.Search the document to find the first
<p>
node using CSS and grab its content:Use a different method name to do the same thing:
Search the document for all
<p>
nodes inside the<body>
tag, and grab the content of the first one.search
returns a nodeset, which is like an array of nodes.This is an important point, and one that trips up almost everyone when first using Nokogiri.
search
and itscss
andxpath
variants return a NodeSet.NodeSet.text
orcontent
concatenates the text of all the returned nodes into a single String which can make it very difficult to take apart again.Using a little different HTML helps illustrate this:
Returning back to the original HTML...
Change the content of the node:
Emit a parsed document as HTML:
Remove a node:
As for scraping, there are a lot of questions on SO about using Nokogiri for tearing apart HTML from sites. Searching StackOverflow for "nokogiri and open-uri" should help.