html - 使用 Nokogiri 抓取整个 HTML 标签

标签 html css ruby html-parsing nokogiri

我到处搜索,我发现的只是用 Nokogiri 做 CSS 选择,我所追求的只是摆脱所有 HTML 标签。

例如这个:

<html>
   <head><title>My webpage</title></head>
   <body>
   <h1>Hello Webpage!</h1>
   <div id="references">
      <p><a href="http://www.google.com">Click here</a> to go to the search engine Google</p>
      <p>Or you can <a href="http://www.bing.com">click here to go</a> to Microsoft Bing.</p>
      <p>Don't want to learn Ruby? Then give <a href="http://learnpythonthehardway.org/">Zed Shaw's Learn Python the Hard Way</a> a try</p>
   </div>

   <div id="funstuff">
      <p>Here are some entertaining links:</p>
      <ul>
         <li><a href="http://youtube.com">YouTube</a></li>
         <li><a data-category="news" href="http://reddit.com">Reddit</a></li>
         <li><a href="http://kathack.com/">Kathack</a></li>
         <li><a data-category="news" href="http://www.nytimes.com">New York Times</a></li>
      </ul>
   </div>

   <p>Thank you for reading my webpage!</p>

   </body>
<p>Addition</p>
</html> 
Extra content

应该输出为:

Hello Webpage!

Click here to go to the search engine Google

Or you can click here to go to Microsoft Bing.

Don't want to learn Ruby? Then give Zed Shaw's Learn Python the Hard Way a try

Here are some entertaining links:

YouTube
Reddit
Kathack
New York Times
Thank you for reading my webpage!
Addition
Extra content

我如何使用 Nokogiri 做到这一点?另外,我还能做些什么来抓取其他代码,例如 Javascript?

最佳答案

require 'nokogiri'

html = %q{ 
  <html>
   <head><title>My webpage</title></head>
   <body>
   <h1>Hello Webpage!</h1>
   <div id="references">
     <p><a href="http://www.google.com">Click here</a> to go to the search engine Google</p>
     <p>Or you can <a href="http://www.bing.com">click here to go</a> to Microsoft Bing.</p>
     <p>Don't want to learn Ruby? Then give <a href="http://learnpythonthehardway.org/">Zed Shaw's    Learn Python the Hard Way</a> a try</p>
   </div>

   <div id="funstuff">
    <p>Here are some entertaining links:</p>
    <ul>
     <li><a href="http://youtube.com">YouTube</a></li>
     <li><a data-category="news" href="http://reddit.com">Reddit</a></li>
     <li><a href="http://kathack.com/">Kathack</a></li>
     <li><a data-category="news" href="http://www.nytimes.com">New York Times</a></li>
     </ul>
   </div>

   <p>Thank you for reading my webpage!</p>

   </body>
</html>
}

doc = Nokogiri::XML(html)
body = doc.search('body')
puts body.text.gsub(/<.*?\/?>/, '')

关于html - 使用 Nokogiri 抓取整个 HTML 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23474479/

相关文章:

ruby - Ruby 的 YAML 模块可以用来嵌入评论吗?

javascript - 如何等待 'end' 事件的 'resize' 然后才执行操作?

html - VS Code 1.24.1 更新后没有 HTML 语言模式

javascript - ReactJS 单击并按住按钮

css - 通过CSS将图像添加到文本左侧

javascript - 从 Ruby on Rails 模型调用 JavaScript 函数

ruby-on-rails - 修复未定义方法的最佳方法

html - 在知道组件字符串名称的 Angular 2 中动态插入组件

python - 抓取页面时找不到视频网址

html - 为什么内容器与外容器不相配?