Created
May 3, 2009 22:23
-
-
Save postmodern/106175 to your computer and use it in GitHub Desktop.
Grabs all the text and <a> tags from a web-page
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'nokogiri' | |
require 'open-uri' | |
require 'cgi' | |
require 'uri' | |
unless ARGV.length == 1 | |
STDERR.puts "usage: ./text_and_links URL" | |
exit -1 | |
end | |
IGNORE_TAGS = ['script', 'style'] | |
def text_and_links(start,ignore=IGNORE_TAGS) | |
buffer = [] | |
iterate = lambda { |root| | |
root.children.each { |node| | |
if node.text? | |
buffer << node.to_html.strip | |
elsif (node.name == 'a' && node['href']) | |
href = URI.escape(node['href']) | |
text = CGI.escapeHTML(node.inner_text) | |
buffer << "<a href=#{href.dump}>#{text}</a>" | |
elsif !(ignore.include?(node.name)) | |
iterate.call(node) | |
end | |
} | |
} | |
iterate.call(start) | |
return buffer.join(' ') | |
end | |
doc = Nokogiri::HTML(open(ARGV[0])) | |
puts text_and_links(doc.at('body')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment