Hackeando pela Diversidade

Dados:

a moeda da Era da Informação

Image: https://publish.illinois.edu/frontiers-big-data-symposium/

Prof. Fernando Masanori

https://gist.github.com/fmasanori

Web Scraping

com Python

Mining the Social Web 2nd edition

Resource: https://github.com/ptwobrussell/Mining-the-Social-Web-2nd-Edition

Web Scraping com Python

Site do livro em inglês: http://pythonscraping.com

 

Código disponível: https://github.com/REMitchell/python-scraping

Periféricas

A ideia do Hackeando pela Diversidade é pensar em soluções que visam melhorar a vida de pessoas do público LGBT, mulheres cis e trans, como também pessoas portadoras de necessidades especiais e em situação de risco.

Repositório do Hack Nights: https://github.com/perifericas/hacknights 

Pad (documento colaborativo) público: https://antonieta.vedetas.org/p/hackeando_diversidade

Raspagem de dados

Introdução

Extração

Limpeza

Análise

Visualização

Image credits: Udemy | Olhares.org

urllib

lxml

HTML Parser

  • Biblioteca Python padrão
  • Solicitar dados na Web
  • Manipulação de cookies
  • Alteração de metadados

JSON

JavaScript Object Notation - www.json.org

  • Modelo para armazenamento e transmissão de informações no formato texto
  • Formato simples que consegue transmitir grande volume de informações de forma compacta

Documentação Python: https://docs.python.org/3/library/json.html​
http://jsonviewer.stack.hu/

Links legais

Sensepedia:

API part 1 e 2 - bit.ly/2ffxEmc

API de AI - bit.ly/2e65UOf

API
(Application Programming Interface)

  • https://dev.twitter.com/pt
  • https://developers.facebook.com/docs/
    graph-api
  • https://developer.github.com/
  • https://www.instagram.com/developer/
  • http://netflix.github.io/

 

Ferramentas para quem não programa (ainda)

  • Jornalismo de Dados
  • Escola de Dados - www.escoladedos.org
  • Import.io
  • Webscraper.io
  • Plugins na Chrome Store
  • Firefox - instalar Firebug (Inspecionar elemento)

LAI

Lei de Acesso à Informação

Mais info em www.acessoainformacao.gov.br

Pedidos através do www.esic.gov.br

 

 

 

Ferramentas

em Python

(myenv) ~ http://bit.ly/1fhx5mq

cd pasta
$ sudo apt-get install virtualenvwrapper
mkvirtualenv nome_da_env

Ou usando apenas virtualenv

cd pasta
$ sudo apt-get install python-virtualenv
virtualenv nome_da_env
source nome_da_env/bin/activate

Para desativar:
deactivate

Beautiful Soup

Biblioteca BS4

Download: https://www.crummy.com/software/BeautifulSoup/

IDLE 1.1.1      
>>> from BeautifulSoup import BeautifulSoup
$sudo apt-get install python-bs4

Python3.x
$sudo python3 setup.py install

Ou pelo pip
(myenv) pip3 install beautifulsoup4

https://scrapy.org

 pip install scrapy

 cat > myspider.py <<EOF

import scrapy

class BlogSpider(scrapy.Spider):
    name = 'blogspider'
    start_urls = ['https://blog.scrapinghub.com']

    def parse(self, response):
        for title in response.css('h2.entry-title'):
            yield {'title': title.css('a ::text').extract_first()}

        next_page = response.css('div.prev-post > a ::attr(href)').extract_first()
        if next_page:
            yield scrapy.Request(response.urljoin(next_page), callback=self.parse)

EOF

 scrapy runspider myspider.py

Ciência de Dados

Python, R e Julia

  • Kaggle - www.kaggle.com
  • Data Camp - www.datacamp.com
  • Data Quest - www.dataquest.io
  • Coursera, Edx e outros

Machine Learning

Processing - py.processing.org

Image credits: http://bit.ly/2eB4R9Q

p5js.org

py.processing.org

android.processing.org

Hora do Código

http://hello.processing.org

Vamos criar um scraper!

from urllib.request import urlopen
html = urlopen("http://raulhc.cc/Agenda/JSON")
print(html.read())

Planejar antes poupa tempo

  • O que quero extrair? 
  • Como extrair?
  • Finalidade?

Executando

  • Pegando os dados
  • Extraindo os dados 
  • Gerando a saída de dados
  • Execução

Resultados

Com Beautiful Soup

from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen("http://oxentimenina.wordpress.com/blog")
bsObj = BeautifulSoup(html.read());
print(bsOj.h1)

Outras chamadas da função:


bsObj.html.body.h1

bsObj.body.h1

bsObj.html.h1

Com Beautiful Soup

from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen("http://oxentimenina.wordpress.com/blog")
bsObj = BeautifulSoup(html.read());
print(bsOj.h1)

Crawler simples by Bernado 

import os
import json
import requests
from bs4 import BeautifulSoup

START_URL = "http://oxentimenina.wordpress.com/blog"

def get_posts_links():
    """
    Returns an iterator with the a tags with the titles
    """
    html = requests.get(START_URL).content
    soup = BeautifulSoup(html)
    return soup.findAll('a', rel='bookmark')

Crawler simples by Bernado 

def extract_data_from_link(post_link_tag):
    """
    Given a tag object, return it href value and post title
    """
    return {
        'link': post_link_tag.attrs['href'],
        'title': post_link_tag.getText(),
    }

def creates_output_file(data):
    """
    Creates a json file with data parameter
    """
    file_path = os.path.join(os.path.dirname(__file__), 'out.json')
    with open(file_path, 'w') as fp:
        json_data = json.dumps(data)
        fp.write(json_data)

Crawler simples by Bernado 

def extract_data_from_link(post_link_tag):
    """
    Given a tag object, return it href value and post title
    """
    return {
        'link': post_link_tag.attrs['href'],
        'title': post_link_tag.getText(),
    }

def creates_output_file(data):
    """
    Creates a json file with data parameter
    """
    file_path = os.path.join(os.path.dirname(__file__), 'out.json')
    with open(file_path, 'w') as fp:
        json_data = json.dumps(data)
        fp.write(json_data)

Crawler simples by Bernado 

if __name__ == '__main__':
    posts = get_posts_links()
    data = []

    for post in posts:
        post_data = extract_data_from_link(post)
        data.append(post_data)

    creates_output_file(data)

Crawler simples by Bernado 

Revisando

  • Requisição: requests
  • Parsing (): beautifulsoup
  • Serialização: JSON

Resultados

O que é um crawler?

Web crawler, em português rastreador web, é um programa de computador que navega pela World Wide Web de uma forma metódica e automatizada.

Outros termos para Web crawlers são indexadores automáticos, bots, web spiders, Web robot, ou Web scutter.

 

Rastreador web – Wikipédia, a enciclopédia livre

https://pt.wikipedia.org/wiki/Rastreador_web

Como funciona um crawler?

Extraindo dados e criando um crawler com Import.io

Tutorial: http://support.import.io/knowledgebase/articles/740868-create-your-first-data-extractor

 

Exemplos: https://magic.import.io/examples
Canal no You Tube:

https://www.youtube.com/channel/UClf0cJlTFWyb5zmsBhjo2lg

Outros exercícios

https://github.com/stanfordjournalism/search-script-scrape

https://gist.github.com/fmasanori


Hackeando pela Diversidade

By Geisa Santos

Hackeando pela Diversidade

In proguess

  • 1,002