Skip to content

Instantly share code, notes, and snippets.

@juque
Created January 20, 2023 03:05
Show Gist options
  • Save juque/fa66ef41f9ca0eae196573eb5ee0992c to your computer and use it in GitHub Desktop.
Save juque/fa66ef41f9ca0eae196573eb5ee0992c to your computer and use it in GitHub Desktop.
Ejemplo de scraping en ruby
# Tarea:
#
# Se tiene una página que muestra información tabulada usando DIVs
# Se quiere convertir a una tabla HTML.
#
# Solución:
#
# Para implementar esta solución nos ayudaremos de dos librerías o gemas
#
# 1. http - https://github.com/httprb/http
#
# y la hiper-conocida en el mundo Ruby...
#
# 2. nokogiri - https://github.com/sparklemotion/nokogiri
#
# Autor:
#
# juque.cl
require 'http'
require 'nokogiri'
# URL a _scrapear_
url = "https://www.farmaciasknop.com/especialistas-santiago/"
# Vamos en búsqueda de la información gracias a la gema http
content = HTTP.follow.get url
# Parseamos el contenido con ayuda de Nokogiri
doc = Nokogiri::HTML content.to_s
# En este arreglo iremos guardando los trozos de TRs
table_rows = []
# Similar a CSS preguntamos por la clase `.entry-content`
# y luego bucleamos sobre sus hijos
doc.css('.entry-content').children.each do |row|
# En este arreglo iremos almacenando los trozos de TDs
# Los cuales son los hijos de row
table_cells = []
row.children.each do |column|
# el método `.content` nos extraerá la información en solo texto,
# además quitamos tabs y espacios en blanco usando `.strip`
# Ref: https://www.rubydoc.info/github/sparklemotion/nokogiri/Nokogiri%2FXML%2FNode:content
table_cells << "<td>#{column.content.strip}</td>"
end
# Todo el arreglo lo pasamos a un string usando `.join`
# Ref: https://www.rubydoc.info/stdlib/core/Array:join
table_rows << "<tr>#{table_cells.join}</tr>"
end
# Finalmente imprimimos la tabla completa
puts "<table>#{table_rows.join}</table>"
# NOTA: escupirá un HTML no muy lindo
# pero puedes usar https://htmltidy.net/ para hacerlo bello :)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment