我到处搜索,我发现的只是用 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/