SlideShare una empresa de Scribd logo
Scraping the Web
the workshop
José Manuel Ortega
@jmortegac
Agenda
Librerías python
BeautifulSoup
Scrapy / Proyectos
Mechanize / Selenium
Herramientas web / plugins
Repositorio Github
https://github.com/jmortega/codemotion_scraping_the_web
Técnicas de scraping
 Screen scraping
 Web scraping
 Report mining
 Spider
Webscraping
 Es el proceso de recolección o extracción de
datos de páginas web de forma automática.
 Técnica que se emplea para extraer
datos usando herramientas de software, está
relacionada con la indexación de información
que está en la web empleando un robot
 Metodología universal adoptada por
la mayoría de los motores de búsqueda.
Python
 http://www.python.org
 Lenguaje de programación interpretado multiparadigma,
soporta orientación a objetos, programación imperativa y, en
menor medida programación funcional.
 Usa tipado dinámico y es multiplataforma.
Librerías Python
 Requests
 Lxml
 Regular expressions
 Beautiful Soup 4
 Pyquery
 Webscraping
 Scrapy
 Mechanize
 Selenium
Request libraries
 Urllib2
 Python requests: HTTP for Humans
 $ pip install requests
Requests http://docs.python-requests.org/en/latest
Requests
Web scraping with Python
1. Download webpage with urllib2,
requests
2. Parse the page with BeautifulSoup/lxml
3. Select with XPath or css selectors
Web scraping with Python
Regular expressions
<h1>(.*?)</h1>
Xpath
//h1
Generar un objeto del HTML (tipo DOM)
page.h1
Regular expressions
 [A-Z] matches a capital letter
 [0-9] matches a number
 [a-z][0-9] matches a lowercase letter followed
by a number
 star * matches the previous item 0 or more times
 plus + matches the previous item 1 or more times
 dot . will match anything but line break
characters r n
 question ? makes the preceeding item optional
BeautifulSoup
 Librería que permite el parseo de páginas web
 Soporta parsers como lxml,html5lib
 Instalación
 pip install lxml
 pip instlal html5lib
 pip install beautifulsoup4
 http://www.crummy.com/software/BeautifulSoup
BeautifulSoup
 soup = BeautifulSoup(html_doc,’lxml’)
 Print all: print(soup.prettify())
 Print text: print(soup.get_text())
from bs4 import BeautifulSoup
BeautifulSoup functions
 find_all(‘a’)Obtiene una lista con todos los enlaces
 find(‘title’)Obtiene el primer elemento <title>
 get(‘href’)Obtiene el valor del atributo href de un
determinado elemento
 (element).text  obtiene el texto asociado al elemento
for link in soup.find_all('a'):
print(link.get('href'))
Extracting links with bs4
https://news.ycombinator.com
Extracting links with bs4
https://news.ycombinator.com
Extracting linkedin info with bs4
Extracting linkedin info with bs4
Extraer datos de la agenda de la pycones
http://2015.es.pycon.org/es/schedule
Extraer datos de la agenda de pycones
Beautiful Soup 4
Google translate
Webscraping library
pip install webscraping
 https://bitbucket.org/richardpenman/webscraping/overview
 http://docs.webscraping.com
 https://pypi.python.org/pypi/webscraping
Extraer datos de la agenda de pycones
webscraping
Scraping the web with python
Scrapy
open-source
Framework que permite crear spiders
para ejecutar procesos de crawling de
pag web
Permite la definición de reglas Xpath
mediante expresiones regulares para la
extracción de contenidos
Basada en la librería twisted
Scrapy
 Simple, conciso
 Extensible
 Señales, middlewares
 Rápido
 IO asíncrona (twisted), parseo en C (libxml2)
 Portable
 Linux, Windows, Mac
 Bien testeado
 778 unit-tests, 80% de cobertura
 Código limpio (PEP-8) y desacoplado
 Zen-friendly / pythónico
Scrapy
Utiliza un mecanismo basado en
expresiones XPath llamado Xpath
Selectors.
Utiliza LXML XPath para encontrar
elementos
Utiliza Twisted para el operaciones
asíncronas
Ventajas scrapy
 Más rápido que mechanize porque utiliza operaciones
asíncronas (emplea Twisted).
 Scrapy tiene un mejor soporte para el parseado del html
 Scrapy maneja mejor caracteres unicode, redirecciones,
respuestas gzipped, codificaciones.
 Caché HTTP integrada.
 Se pueden exportar los datos extraídos directamente a csv o
JSON.
Scrapy
XPath selectors
Xpath selectors
Expression Meaning
name matches all nodes on the current level with the
specified name
name[n] matches the nth element on the current level with
the specified name
/ Do selection from the root
// Do selection from current node
* matches all nodes on the current level
. Or .. Select current / parent node
@name the attribute with the specified name
[@key='value'] all elements with an attribute that matches the
specified key/value pair
name[@key='value'] all elements with the specified name and an
attribute that matches the specified key/value pair
[text()='value'] all elements with the specified text
name[text()='value'] all elements with the specified name and text
Scrapy
 Cuando usamos Scrapy tenemos que crear un
proyecto, y cada proyecto se compone de:
 Items Definimos los elementos a extraer.
 Spiders Es el corazón del proyecto, aquí definimos
el procedimiento de extracción.
 Pipelines Son los elementos para analizar lo
obtenido: validación de datos, limpieza del código
html
Architecture
Architecture
Instalación de scrapy
Python 2.6 / 2.7
Lxml
openSSL
pip / easy_install
$ pip install scrapy
$ easy_install scrapy
Instalación de scrapy
pip install scrapy
Scrapy Shell (no es necesario crear proyecto)
scrapy shell <url>
from scrapy.select import Selector
hxs = Selector(response)
Info = hxs.select(‘//div[@class=“slot-inner”]’)
Scrapy Shell
scrapy shell http://scrapy.org
Projecto scrapy
$ scrapy startproject <project_name>
scrapy.cfg: the project configuration file.
tutorial/:the project’s python module.
items.py: the project’s items file.
pipelines.py : the project’s pipelines file.
setting.py : the project’s setting file.
spiders/ : a directory where you’ll later put your spiders.
Scrapy europython
http://ep2015.europython.eu/en/events/sessions
Items
Crear Spider
 $ scrapy genspider -t basic <YOUR SPIDER NAME>
<DOMAIN>
 $ scrapy list
Listado de spiders de un proyecto
Spider
Pipeline
 ITEM_PIPELINES =
[‘<your_project_name>.pipelines.<your_pipeline_classname>']
 pipelines.py
Pipeline SQLite
EuropythonSQLitePipeline
Pipeline SQLite
EuropythonSQLitePipeline
Pipeline SQLite
Europython project GTK
Ejecución
$ scrapy crawl <spider_name>
$ scrapy crawl <spider_name> -o items.json -t json
$ scrapy crawl <spider_name> -o items.csv -t csv
$ scrapy crawl <spider_name> -o items.xml -t xml
Slidebot
$ scrapy crawl -a url="" slideshare
$ scrapy crawl -a url="" speakerdeck
Spider SlideShare
Slidebot
Slidebot
$ scrapy crawl -a
url="http://www.slideshare.net/jmoc25/testing-android-security"
slideshare
Write CSV /JSON
import csv
with open(‘file.csv’,‘wb’) as csvfile:
writer=csv.writer(csvfile)
for line in list:
writer.writerow(line)
import json
with open(‘file.json’,‘wb’) as jsonfile:
json.dump(results,jsonfile)
Fix encode errors
myvar.encode("utf-8")
Scrapyd
 Scrapy web service daemon
$ pip install scrapyd
 Web API with simple Web UI:
http://localhost:6800
 Web API Documentation:
 http://scrapyd.readthedocs.org/en/latest/api.html
Mechanize
 https://pypi.python.org/pypi/mechanize
pip install mechanize
 Mechanize permite navegar por los enlaces
de forma programática
Mechanize
import mechanize
# service url
URL = ‘’
def main():
# Create a Browser instance
b = mechanize.Browser()
# Load the page
b.open(URL)
# Select the form
b.select_form(nr=0)
# Fill out the form
b[key] = value
# Submit!
return b.submit()
Mechanize
mechanize._response.httperror_see
k_wrapper: HTTP Error 403:
request disallowed by robots.txt
browser.set_handle_robots(False)
Mechanize netflix login
Mechanize utils
Mechanize search in duckduckgo
Mechanize extract links
import mechanize
br = mechanize.Browser()
response = br.open(url)
for link in br.links():
print link
Alternatives for mechanize
 RoboBrowser
 https://github.com/jmcarp/robobrowser
 MechanicalSoup
 https://github.com/hickford/MechanicalSoup
Robobrowser
 Basada en BeatifulSoup
 Emplea la librería requests
 Compatible con python 3
Robobrowser
Robobrowser
Mechanical soup
Selenium
 Open Source framework for automating
browsers
 Python-Module
http://pypi.python.org/pypi/selenium
 pip install selenium
 Firefox-Driver
Selenium
 Open a browser
 Open a Page
Selenium
 find_element_
by_link_text(‘text’): find the link by text
by_css_selector: just like with lxml css
by_tag_name: ‘a’ for the first link or all links
by_xpath: practice xpath regex
by_class_name: CSS related, but this finds
all different types that have the same class
Selenium
<div id=“myid">...</div>
browser.find_element_by_id(“myid")
<input type="text" name="example" />
browser.find_elements_by_xpath("//input")
<input type="text" name="example" />
browser.find_element_by_name(“example")
Selenium
<div id=“myid">
<span class=“myclass">content</span>
</div>
browser. find_element_by_css_selector("#myid
span.myclass")
<a href="">content</a>
browser.find_element_by_link_text("content")
Selenium
element.click()
element.submit()
Selenium in codemotion agenda
Extraer datos de la agenda de codemotion
Extraer datos de la agenda de codemotion
Selenium Cookies
Selenium youtube
Selenium youtube
Kimono
Kimono
Scraper Chrome plugin
Scraper Chrome plugin
Scraper Chrome plugin
Parse Hub
Parse Hub
Parse Hub
Web Scraper plugin http://webscraper.io
Web Scraper plugin
XPath expressions
 Plugins para firefox
 FireFinder for FireBug
 FirePath
XPath expressions
 Xpath Helper
 Mover el mouse + tecla shift
 Obtener la expresión xpath de un determinado
elemento html
XPath expressions
Scraping Hub
 Scrapy Cloud es una plataforma para la implementación,
ejecución y seguimiento de las arañas Scrapy y un
visualizador de los datos scrapeados.
 Permite controlar las arañas mediante tareas programadas,
revisar que procesos están corriendo y obtener los datos
scrapeados.
 Los proyectos se pueden gestionan desde la API o a través
de su Panel Web.
Scrapy Cloud
http://doc.scrapinghub.com/scrapy-cloud.html
https://dash.scrapinghub.com
>>pip install shub
>>shub login
>>Insert your ScrapingHub API Key:
Scrapy Cloud /scrapy.cfg
# Project: demo
[deploy]
url =https://dash.scrapinghub.com/api/scrapyd/
#API_KEY
username = ec6334d7375845fdb876c1d10b2b1622
password =
project = 25767
Scrapy Cloud
Scrapy Cloud
Scrapy Cloud
Scrapy Cloud
Scrapy Cloud Scheduling
curl -u APIKEY:
https://dash.scrapinghub.com/api/schedule.json -d
project=PROJECT -d spider=SPIDER
Referencias
 http://www.crummy.com/software/BeautifulSoup
 http://scrapy.org
 https://pypi.python.org/pypi/mechanize
 http://docs.python-requests.org/en/latest
 http://selenium-
python.readthedocs.org/index.html
 https://github.com/REMitchell/python-scraping
Books

Más contenido relacionado

PDF
Tricks every ClickHouse designer should know, by Robert Hodges, Altinity CEO
PDF
ClickHouse Data Warehouse 101: The First Billion Rows, by Alexander Zaitsev a...
PPTX
DataFrame in Python Pandas
PDF
Sql Antipatterns Strike Back
PPTX
Advanced Python : Decorators
PDF
Automating Predictive Modeling at Zynga with PySpark and Pandas UDFs
PPTX
The executable formats (PE, ELF, HEX, SREC AND ...)
PDF
Webinar: Secrets of ClickHouse Query Performance, by Robert Hodges
Tricks every ClickHouse designer should know, by Robert Hodges, Altinity CEO
ClickHouse Data Warehouse 101: The First Billion Rows, by Alexander Zaitsev a...
DataFrame in Python Pandas
Sql Antipatterns Strike Back
Advanced Python : Decorators
Automating Predictive Modeling at Zynga with PySpark and Pandas UDFs
The executable formats (PE, ELF, HEX, SREC AND ...)
Webinar: Secrets of ClickHouse Query Performance, by Robert Hodges

La actualidad más candente (20)

PDF
Matplotlib Review 2021
PPTX
High Performance, High Reliability Data Loading on ClickHouse
PDF
Arrays In Python | Python Array Operations | Edureka
PPTX
Introduction to matplotlib
ODP
Lisa 2015-gluster fs-hands-on
PPTX
Introduction to numpy Session 1
PPTX
Python - Numpy/Pandas/Matplot Machine Learning Libraries
PPTX
Introduction to pandas
PDF
ClickHouse Monitoring 101: What to monitor and how
PDF
MongoDB World 2019: Tips and Tricks++ for Querying and Indexing MongoDB
PPTX
Python pandas Library
PPTX
Oops concept in c++ unit 3 -topic 4
PPTX
Data Analysis with Python Pandas
PDF
Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...
PDF
How to use Map() Filter() and Reduce() functions in Python | Edureka
PPTX
Building a Distributed Reservation System with Cassandra (Andrew Baker & Jeff...
PDF
Deep Dive on ClickHouse Sharding and Replication-2202-09-22.pdf
PPTX
Python for data analysis
PDF
[Pgday.Seoul 2017] 8. PostgreSQL 10 새기능 소개 - 김상기
PDF
Data warehouse on Kubernetes - gentle intro to Clickhouse Operator, by Robert...
Matplotlib Review 2021
High Performance, High Reliability Data Loading on ClickHouse
Arrays In Python | Python Array Operations | Edureka
Introduction to matplotlib
Lisa 2015-gluster fs-hands-on
Introduction to numpy Session 1
Python - Numpy/Pandas/Matplot Machine Learning Libraries
Introduction to pandas
ClickHouse Monitoring 101: What to monitor and how
MongoDB World 2019: Tips and Tricks++ for Querying and Indexing MongoDB
Python pandas Library
Oops concept in c++ unit 3 -topic 4
Data Analysis with Python Pandas
Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...
How to use Map() Filter() and Reduce() functions in Python | Edureka
Building a Distributed Reservation System with Cassandra (Andrew Baker & Jeff...
Deep Dive on ClickHouse Sharding and Replication-2202-09-22.pdf
Python for data analysis
[Pgday.Seoul 2017] 8. PostgreSQL 10 새기능 소개 - 김상기
Data warehouse on Kubernetes - gentle intro to Clickhouse Operator, by Robert...
Publicidad

Destacado (8)

ODP
Linux Introduction (Commands)
PPT
Hadoop introduction 2
PDF
Tutorial on Web Scraping in Python
PDF
Linux File System
PPTX
Linux.ppt
PPTX
Big Data & Hadoop Tutorial
PDF
Web Scraping with Python
Linux Introduction (Commands)
Hadoop introduction 2
Tutorial on Web Scraping in Python
Linux File System
Linux.ppt
Big Data & Hadoop Tutorial
Web Scraping with Python
Publicidad

Similar a Scraping the web with python (20)

PDF
Python para desarrolladores web
PPTX
Taller de Scrapy - Barcelona Activa
PPTX
Scraping avanzado o Cómo hacer de internet tu base de datos #seoplus2018
PDF
Desarrollo aplicaciones web con python de forma nativa
PDF
Tutorial CodeIgniter + Netbeans 7
PDF
Introducción al desarrollo Web: Frontend con Angular 6
PDF
Primeros pasos Symfony PHPVigo
PPTX
Evolution INTech - Acceso a bases de datos con Minimal APIs de .NET 6.pptx
PPTX
Cybercamp 2015 - Python, hacking y sec-tools desde las trincheras
PPTX
Vamos a desplejar Angular+ 16 con Netlify
PPTX
IT Camps Apps Office 365 Valencia 2014
PDF
PDF
Cien usos con serverless
PPT
Symfony Parte 2
PPTX
PowerShell para SharePoint OnPremises y Online, la herramienta compartida por...
PDF
Screen scraping
PDF
Aplicaciones Web
PPTX
Collab365 - Como hacer de todo con PowerShell en SharePoint (OnPremises y On...
Python para desarrolladores web
Taller de Scrapy - Barcelona Activa
Scraping avanzado o Cómo hacer de internet tu base de datos #seoplus2018
Desarrollo aplicaciones web con python de forma nativa
Tutorial CodeIgniter + Netbeans 7
Introducción al desarrollo Web: Frontend con Angular 6
Primeros pasos Symfony PHPVigo
Evolution INTech - Acceso a bases de datos con Minimal APIs de .NET 6.pptx
Cybercamp 2015 - Python, hacking y sec-tools desde las trincheras
Vamos a desplejar Angular+ 16 con Netlify
IT Camps Apps Office 365 Valencia 2014
Cien usos con serverless
Symfony Parte 2
PowerShell para SharePoint OnPremises y Online, la herramienta compartida por...
Screen scraping
Aplicaciones Web
Collab365 - Como hacer de todo con PowerShell en SharePoint (OnPremises y On...

Más de Jose Manuel Ortega Candel (20)

PDF
Seguridad y auditorías en Modelos grandes del lenguaje (LLM)
PDF
Seguridad y auditorías en Modelos grandes del lenguaje (LLM).pdf
PDF
Beyond the hype: The reality of AI security.pdf
PDF
Seguridad de APIs en Drupal_ herramientas, mejores prácticas y estrategias pa...
PDF
Security and auditing tools in Large Language Models (LLM).pdf
PDF
Herramientas de benchmarks para evaluar el rendimiento en máquinas y aplicaci...
PDF
Asegurando tus APIs Explorando el OWASP Top 10 de Seguridad en APIs.pdf
PDF
PyGoat Analizando la seguridad en aplicaciones Django.pdf
PDF
Ciberseguridad en Blockchain y Smart Contracts: Explorando los Desafíos y Sol...
PDF
Evolution of security strategies in K8s environments- All day devops
PDF
Evolution of security strategies in K8s environments.pdf
PDF
Implementing Observability for Kubernetes.pdf
PDF
Computación distribuida usando Python
PDF
Seguridad en arquitecturas serverless y entornos cloud
PDF
Construyendo arquitecturas zero trust sobre entornos cloud
PDF
Tips and tricks for data science projects with Python
PDF
Sharing secret keys in Docker containers and K8s
PDF
Implementing cert-manager in K8s
PDF
Python para equipos de ciberseguridad(pycones)
PDF
Python para equipos de ciberseguridad
Seguridad y auditorías en Modelos grandes del lenguaje (LLM)
Seguridad y auditorías en Modelos grandes del lenguaje (LLM).pdf
Beyond the hype: The reality of AI security.pdf
Seguridad de APIs en Drupal_ herramientas, mejores prácticas y estrategias pa...
Security and auditing tools in Large Language Models (LLM).pdf
Herramientas de benchmarks para evaluar el rendimiento en máquinas y aplicaci...
Asegurando tus APIs Explorando el OWASP Top 10 de Seguridad en APIs.pdf
PyGoat Analizando la seguridad en aplicaciones Django.pdf
Ciberseguridad en Blockchain y Smart Contracts: Explorando los Desafíos y Sol...
Evolution of security strategies in K8s environments- All day devops
Evolution of security strategies in K8s environments.pdf
Implementing Observability for Kubernetes.pdf
Computación distribuida usando Python
Seguridad en arquitecturas serverless y entornos cloud
Construyendo arquitecturas zero trust sobre entornos cloud
Tips and tricks for data science projects with Python
Sharing secret keys in Docker containers and K8s
Implementing cert-manager in K8s
Python para equipos de ciberseguridad(pycones)
Python para equipos de ciberseguridad

Último (20)

PPTX
Gestion de seguridad y salud ocupacional.pptx
PPT
357161027-seguridad-industrial-diapositivas-ppt.ppt
PDF
Curso Introductorio de Cristales Liquidos
PDF
Primera formulación de cargos de la SEC en contra del CEN
PPTX
A8B08CED-D3D9-415C-B4A3-2A6CA6409A48.1.1Presentación Dirección 2022 unidade...
PPTX
376060032-Diapositivas-de-Ingenieria-ESTRUCTURAL.pptx
PPTX
clase MICROCONTROLADORES ago-dic 2019.pptx
PPTX
Logging While Drilling Ingenieria Petrolera.pptx
PPTX
Seminario de telecomunicaciones para ingeniería
PPTX
leyes de los gases Ideales. combustible refinación
PDF
presentacion sobre los polimeros, como se conforman
DOCX
CONCEPTOS BASICOS DE LA PROGRAMACION STEP
PDF
Informe Estudio Final Apagon del 25 de febrero
PPTX
NILS actividad 4 PRESENTACION.pptx pppppp
PDF
Copia de Presentación Propuesta de Marketing Corporativo Blanco y Negro.pdf
PPTX
1 CONTAMINACION AMBIENTAL EN EL PLANETA.pptx
PDF
prg2_t01_p01_Fundamentos POO - parte1.pdf
PDF
Pensamiento Politico Siglo XXI Peru y Mundo.pdf
PPTX
MARITIMO Y LESGILACION DEL MACO TRANSPORTE
PPTX
Presentación - Taller interpretación iso 9001-Solutions consulting learning.pptx
Gestion de seguridad y salud ocupacional.pptx
357161027-seguridad-industrial-diapositivas-ppt.ppt
Curso Introductorio de Cristales Liquidos
Primera formulación de cargos de la SEC en contra del CEN
A8B08CED-D3D9-415C-B4A3-2A6CA6409A48.1.1Presentación Dirección 2022 unidade...
376060032-Diapositivas-de-Ingenieria-ESTRUCTURAL.pptx
clase MICROCONTROLADORES ago-dic 2019.pptx
Logging While Drilling Ingenieria Petrolera.pptx
Seminario de telecomunicaciones para ingeniería
leyes de los gases Ideales. combustible refinación
presentacion sobre los polimeros, como se conforman
CONCEPTOS BASICOS DE LA PROGRAMACION STEP
Informe Estudio Final Apagon del 25 de febrero
NILS actividad 4 PRESENTACION.pptx pppppp
Copia de Presentación Propuesta de Marketing Corporativo Blanco y Negro.pdf
1 CONTAMINACION AMBIENTAL EN EL PLANETA.pptx
prg2_t01_p01_Fundamentos POO - parte1.pdf
Pensamiento Politico Siglo XXI Peru y Mundo.pdf
MARITIMO Y LESGILACION DEL MACO TRANSPORTE
Presentación - Taller interpretación iso 9001-Solutions consulting learning.pptx

Scraping the web with python