Canais iMasters

Linguagens + Desenvolvimento

Ruby Snapshot: imagens do momento

Estou voltando depois de muito tempo sem escrever. Dei aula à noite durante dois meses e isso me exigiu uma atenção especial. E nada melhor do que voltar com Ruby!

Como vocês já devem ter percebido adoro scripts. Gosto de  automatizar algumas tarefas que costumo realizar várias vezes ao dia.

Às vezes vou até a página da Globo.com ver o que está acontecendo no mundo. Mas tem muita informação na tela pra quem só corre o olho e metade é Big Brother (pelo menos era, quando escrevi isso).

Para me ajudar, fiz um script que resume a página da Globo.com pegando apenas suas imagens. Como sempre faço primeiro vou colocar o script e depois explico:

require 'hpricot'require 'open-uri'
 html = '<html><head><title>Agora no Globo.com</title>'
html += '<META http-equiv="Content-Type" content="text/html;charset=UTF-8"></head>'
html += '<body><h1>Agora</h1><h2>no Globo.com</h2>' 
doc = Hpricot open('http://www.globo.com')
 doc.search 'img' do |img|
  img['src'] = "http://www.globo.com#{img['src']}" unless img['src'].include?('globo.com')
  html += img.to_send
 html += '</body></html>' 
File.open('Agora.html', 'w') { |file| file << html }
 # system 'explorer Agora.html'

Primeiramente percebe-se que utilizei o Hpricot para fazer parse do HTML. Excelente, diga-se. A variável html serve para concatenar o HTML que o script vai gerar.

Na linha 8 faço uma leitura na página Globo.com, utilizo Hpricot e open-uri para isso. Na linha 10 busco todas as imagens da página. Na linha 11 faço uma verificação na url da imagem para ver se é absoluta (http://www.globo.com/imagem.jpg) ou relativa (/imagem.jpg), transformando todas em urls absolutas para serem visualizadas de fora do servidor da Globo.

Finalizo o HTML que geramos e na linha 17 salvo em um arquivo chamado "Agora.html". Quem está utilizando o Windows pode descomentar a linha 19, para abrir o Internet Explorer (Eca!) com esse arquivo.

Você pode, facilmente, alterar o script e buscar as imagens de outro portal, como o Terra, por exemplo. Modifique e comente Até mais.


Comente também

5 Comentários

Victor
Victor

belo post

Pode ajudar com o erro?

C:\Ruby187\Exemplo>ruby Script_img.rb
Script_img.rb:1: syntax error, unexpected tIDENTIFIER, expecting $end
require 'hpricot' require 'open-uri'
^

Victor
Victor

require 'hpricot'
require 'open-uri'

html = '<html><head><title>Agora no Globo.com</title>'
html += '<META http-equiv="Content-Type" content="text/html;charset=UTF-8"></head>'
html += '<body><h1>Agora</h1><h2>no Globo.com</h2>'

doc = Hpricot open('http://www.globo.com')
doc.search 'img' do |img|
img['src'] = "http://www.globo.com#{img['src']}" unless img['src'].include?('globo.com')
html += img.to_send
html += '</body></html>'

File.open('Agora.html', 'w') { |file| file << html }
end
system 'explorer Agora.html'

----------------------------------------------------------
Agora com outro erro.....

C:\Ruby187\Exemplo>ruby Script_img.rb
Script_img.rb:1:in `require': no such file to load -- hpricot (LoadError)
from Script_img.rb:1


Victor
Victor

require 'rubygems'
require 'hpricot'
require 'open-uri'

html = '<html><head><title>Agora no Globo.com</title>'
html += '<META http-equiv="Content-Type" content="text/html;charset=UTF-8"></head>'
html += '<body><h1>Agora</h1><h2>no Globo.com</h2>'

url='http://www.globo.com'

doc = Hpricot(open(url))

doc.search 'img' do |img|

img['src'] = "http://www.globo.com#{img['src']}" unless img['src'].include?('globo.com')
html += img.to_send
html += '</body></html>'

File.open('Agora.html', 'w') { |file| file << html }
end
system 'explorer Agora.html'
------------------------------------------------

C:\Ruby187\Exemplo>ruby Script_img.rb
Script_img.rb:16: undefined method `each' for #<Hpricot::Elem:0x3daf7c0> (NoMeth
odError)
from C:/Ruby187/lib/ruby/gems/1.8/gems/hpricot-0.8.4/lib/hpricot/travers
e.rb:331:in `each'
from C:/Ruby187/lib/ruby/gems/1.8/gems/hpricot-0.8.4/lib/hpricot/travers
e.rb:331:in `search'
from Script_img.rb:13

Victor
Victor


require 'rubygems'
require 'hpricot'
require 'open-uri'

html = '<html><head><title>Agora no Globo.com</title>'
html += '<META http-equiv="Content-Type" content="text/html;charset=UTF-8"></head>'
html += '<body><h1>Agora</h1><h2>no Globo.com</h2>'

url='http://www.globo.com'

doc = Hpricot(open(url))

doc.search 'img' do |img|

img['src'] = "http://www.globo.com#{img['src']}" unless img['src'].include?('globo.com')
html += img.to_send
html += '</body></html>'

File.open('Agora.html', 'w') { |file| file << html }
end
system 'explorer Agora.html'
------------------------------------------------

C:\Ruby187\Exemplo>ruby Script_img.rb
Script_img.rb:16: undefined method `to_send' for #<Hpricot::Elem:0x49cef90> (NoM
ethodError)
from C:/Ruby187/lib/ruby/gems/1.8/gems/hpricot-0.8.4/lib/hpricot/travers
e.rb:331:in `each'
from C:/Ruby187/lib/ruby/gems/1.8/gems/hpricot-0.8.4/lib/hpricot/travers
e.rb:331:in `search'
from Script_img.rb:13

Victor
Victor

require 'rubygems'
require 'hpricot'
require 'open-uri'

html = '<html><head><title>Agora no Globo.com</title>'
html += '<META http-equiv="Content-Type" content="text/html;charset=UTF-8"></head>'
html += '<body><h1>Agora</h1><h2>no Globo.com</h2>'

url='http://www.globo.com'

doc = Hpricot(open(url))

doc.search 'img' do |img|

img['src'] = "http://www.globo.com#{img['src']}" unless img['src'].include?('globo.com')
html += img.to_send
html += '</body></html>'

File.open('Agora.html', 'w') { |file| file << html }
end
system 'explorer Agora.html'

----------------------------------------
C:/RailsInstaller/Ruby1.9.2/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:
36:in `require': no such file to load -- hpricot (LoadError)
from C:/RailsInstaller/Ruby1.9.2/lib/ruby/site_ruby/1.9.1/rubygems/custo
m_require.rb:36:in `require'
from script.rb:2:in `<main>'

Poderia ajudar????

Qual a sua opinião?

Comentários considerados ofensivos serão moderados.
KingHost

Parceiros

IBM
PagSeguro
Internet Innovation
Dialhost
HostNet
Tecla
KingHost
DotStore
Dinamize