Created
August 7, 2011 23:30
-
-
Save jaksonmoura/1130928 to your computer and use it in GitHub Desktop.
Capturando informações de um site
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
| # encoding: UTF-8 | |
| require 'net/http' | |
| require 'open-uri' | |
| class Http | |
| # Responsável pela execução da aplicação | |
| def run | |
| puts "==== Bem-vindo! ====\n" + "Por favor, digite um site:" | |
| www = gets.chomp | |
| get_data(www) | |
| puts "Vamos baixar uma image de #{www}." | |
| puts "Qual o local do arquivo? (ex.: /imagem/image.png)" | |
| file = gets.chomp | |
| puts "Qual o nome do arquivo novo? (padrão = novo)" | |
| nome = gets.chomp | |
| get_file(www, nome) | |
| get_links(www) | |
| puts "Também já foi gerado um arquivo txt com os links encontrados\n" \ | |
| "neste site. De nada!" | |
| end | |
| # | |
| def format_site(www) | |
| return www unless www.match(/http/).nil? | |
| return "http://#{www}" if www.match(/http/).nil? | |
| end | |
| # Captura dados do site | |
| def get_data(www) | |
| begin | |
| uri = URI.parse(format_site(www)) | |
| io = Net::HTTP.start(uri.host, uri.port) {|h| h.get(uri.request_uri)} | |
| puts "Dados do site #{www}.\n"+ | |
| "Status: #{io.header}"+"\n" + | |
| "Versão do HTTP: #{io.http_version}\n" + | |
| "Charset: #{io['content-type']}\n" + | |
| "Tamanho da resposta: #{io.content_length}\n" + | |
| "================================\n" + | |
| "Cabeçalho completo:\n" + | |
| "Server: #{io['server']}\n" + | |
| "Date: #{io['date']}\n" + | |
| "Connection: #{io['connection']}" | |
| return io | |
| rescue | |
| puts "==== Alguma coisa deu errado! Vamos recomeçar! ====\n" | |
| run | |
| end | |
| end | |
| # Baixa uma imagem do site | |
| def get_file(www, nome) | |
| Net::HTTP.start(www) { |http| resp = http.get(file) } | |
| nome = "novo" if nome.empty? | |
| begin | |
| puts open("#{nome}.#{www[-3,3]}", "wb") { |f| | |
| return "ok" if f.write(resp.body) > 0 | |
| } | |
| rescue | |
| puts "==== Não consegui salvar a imagem! ====" \ | |
| end | |
| end | |
| # | |
| def get_links(www) | |
| a = open(format_site(www)) | |
| i = 0 | |
| File.new("links.txt") | |
| File.open("links.txt", "wb") { |f| | |
| f.write "Links encontrados!\n\n" | |
| a.each_line do |line| | |
| if line.match(/<a /) | |
| @tmp = "" | |
| b = line.index("href=\"") | |
| c = b+6 | |
| c.upto(line.length-1) do |s| | |
| if line[s,1] != "\"" | |
| @tmp << line[s,1] | |
| end | |
| if line[s,1] == "\"" | |
| break | |
| end | |
| end | |
| puts "Link: #{@tmp}" | |
| f.write("#{@tmp}\n") | |
| i += 1 | |
| end | |
| end | |
| f.close } | |
| end | |
| end | |
| #Rodando a Aplicação | |
| Http.new.run |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment