Introduction to WebScraping Workshop - Semcomp 24 Beta

Overview

O que é WebScraping?

Extrair informações da internet de forma automatizada. Existem diversas maneiras de fazer isso, nesse tutorial vamos ver algumas delas, por meio de bibliotecas de python.

Porque é útil?

  • Automatizar processos
  • Gerar Leads
  • Acompanhar produtos
  • Fazer projetos!!!

É legal?

Bom, é legal, mas nem sempre é legal. Em geral, criar web scrapers é muito divertido, mas nem sempre é uma coisa legalizada. Por isso é importante ficar atento aos termos de uso dos sites. O linkedin, por exemplo, não permite que sejam utilizados scrapers em nenhuma situação.

Quais as ferramentas utilizadas nesse tutorial?

Todos os códigos são feitos em Python 3. Além disso, são utilizadas algumas bibliotecas, as principais são:

Outras bibliotecas são utilizadas de apoio, e para instalar tudo, basta utilizar o arquivo requirements.txt presente nesse repositório por meio do comando:

pip3 install -r requirements.txt

O projeto

O projeto tem uma ideia bem direta: descobrir quais palavras os artistas mais utilizam em suas músicas. Para isso vamos scrapar o site letras.mus, buscando todas as músicas de um dado artista.

Versão 1

Nessa versão do projeto, pegamos as letras do letras.mus e contamos a palavras.

Versão 2

A segunda versão do projeto envolve pegar os artistas mais relevantes do lastfm e, para cada um desses artistas, fazer a contagem das palavras. Nessa versão usamos requests-html para renderizar a página.

Versão 3

Na terceira versão do projeto, fazemos o mesmo que na versão 2, porém dessa vez é feita a requisição direto em um endpoint com a biblioteca requests.

Versão 4

A última versão do projeto envolve buscar a quantidade de ouvintes mensais dos artistas no spotify. Para isso usamos selenium.

Sobre as ferramentas

Requests

  • Biblioteca para fazer requisições web.
  • Pode ser utilizada para get, post, delete...
  • Precisa de outra biblioteca para fazer parsing do html.

Lxml

  • Biblioteca para fazer parsing do html.
  • Útil pois permite busca por xpath de forma nativa.
  • Minha queridinha s2

BeautifulSoup

  • Biblioteca para fazer parsing do html.
  • Tem muita documentação e perguntas na internet (alo stackoverflow)
  • É bem flexível, permite o uso de diversos parsers, mas não tem xpath =(

Requests-html

  • Em muitos casos só a requisição não basta. É preciso também renderizar o javascript da página. A biblioteca requests não tem essa funcionalidade.
  • A requests-html pode ser usada da mesma maneira que a requests, mas possui essa nova funcionalidade de renderização.
  • Precisa de outra biblioteca para fazer parsing do html (pode usar qualquer uma das duas citadas acima).

Selenium

  • Selenium é uma ferramenta de automatização de software e é muito utilizada para realização de testes. MAS é super útil para scraping também.
  • Como o software simula um navegador, muitas vezes "engana" melhor os antibots. Além disso, renderiza o javascript normalmente, então serve para esses casos também.
  • Na maioria das vezes, usar selenium é matar uma barata com um canhão, mas em alguns momentos pode ser útil.
  • Truque: se nada que você fizer funcionar naquele site, tenta usar o selenium e fazer requisições para outros sites com aquele driver. Isso vai gerar cookies no navegador e vai ser mais fácil se passar por um usuário comum.

Truque endpoint

  • Um dos melhores truques de scraping é buscar enpoints na aba de network do navegador.
  • Isso permite fazer uma requisição direta sem precisar fazer parsing de html, o que facilita nossa vida e ainda é mais rápido.
  • É o jeito mais fácil de codar, mas as vezes exige paciência para encontrar o endpoint certo.
  • Para o código basta:
    1. Clicar em network
    2. Encontrar endpoint
    3. Clicar com botão direito
    4. Clicar em "Copiar como Curl"
    5. Ir para esse site
    6. Copiar resultado como requests
    7. Ta pronto o sorvetinho

Passo a passo que >eu< uso

Onde aprender mais?

Existem muuuuitos sites com tutoriais por aí, mas eu gosto bastante de usar o Medium para aprender esse tipo de coisa. Algumas sugestões de texto são:

Além disso, também tem esse projeto guiado no Coursera que é bem legal.

No mais, pega alguns sites e vai tentando. Se der errado, pesquisa no StackOverflow e tenta entender o que rolou, isso é um processo importante também!

E uma última dica, tem muuuitos sites diferentes por ai, cada um com sua própria peculiaridade. Não dá para aprender TUDO de scraping sem ir treinando, então recomendo aprender o básico e depois ir pesquisando sob demanda as coisas mais complexas =D

Último aviso

Vocês tem meus contatos, então podem ficar a vontade pra mandar mensagem/email sempre que precisarem =D

Owner
Luísa Moura
Luísa Moura
This is a sport analytics project that combines the knowledge of OOP and Webscraping

This is a sport analytics project that combines the knowledge of Object Oriented Programming (OOP) and Webscraping, the weekly scraping of the English Premier league table is carried out to assess th

Dolamu Oludare 1 Nov 26, 2021
Video Games Web Scraper is a project that crawls websites and APIs and extracts video game related data from their pages.

Video Games Web Scraper Video Games Web Scraper is a project that crawls websites and APIs and extracts video game related data from their pages. This

Albert Marrero 1 Jan 12, 2022
This code will be able to scrape movies from a movie website and also provide download links to newly uploaded movies.

Movies-Scraper You are probably tired of navigating through a movie website to get the right movie you'd want to watch during the weekend. There may e

1 Jan 31, 2022
Libextract: extract data from websites

Libextract is a statistics-enabled data extraction library that works on HTML and XML documents and written in Python

499 Dec 09, 2022
Scrapy-based cyber security news finder

Cyber-Security-News-Scraper Scrapy-based cyber security news finder Goal To keep up to date on the constant barrage of information within the field of

2 Nov 01, 2021
A Web Scraper built with beautiful soup, that fetches udemy course information. Get udemy course information and convert it to json, csv or xml file

Udemy Scraper A Web Scraper built with beautiful soup, that fetches udemy course information. Installation Virtual Environment Firstly, it is recommen

Aditya Gupta 15 May 17, 2022
Haphazard scripts for scraping bitcoin/bitcoin data from GitHub

This is a quick-and-dirty tool used to scrape bitcoin/bitcoin pull request and commentary data. Each output/pr number folder contains comments.json:

James O'Beirne 8 Oct 12, 2022
Python script that reads Aliexpress offers urls from a Excel filename (.csv) and post then in a Telegram channel using a bot

Aliexpress to telegram post Python script that reads Aliexpress offers urls from a Excel filename (.csv) and post then in a Telegram channel using a b

Fernando 6 Dec 06, 2022
Web3 Pancakeswap Sniper bot written in python3

Pancakeswap_BSC_Sniper_Bot Web3 Pancakeswap Sniper bot written in python3, Please note the license conditions! The first Binance Smart Chain sniper bo

Treading-Tigers 295 Dec 31, 2022
CRI Scrape is a tool for get general info about Italian Red Cross in GAIA Platform

CRI Scrape CRI Scrape is a tool for get general info about Italian Red Cross in GAIA Platform Disclaimer This code is only for educational purpose. So

Vincenzo Cardone 0 Jul 23, 2022
此脚本为 python 脚本,实现原理为利用 selenium 定位相关元素,再配合点击事件完成浏览器的自动化.

此脚本为 python 脚本,实现原理为利用 selenium 定位相关元素,再配合点击事件完成浏览器的自动化.

N0el4kLs 5 Nov 19, 2021
Python web scrapper

Website scrapper Web scrapping project in Python. Created for learning purposes. Start Install python Update configuration with websites Launch script

Nogueira Vitor 1 Dec 19, 2021
A tool to easily scrape youtube data using the Google API

YouTube data scraper To easily scrape any data from the youtube homepage, a youtube channel/user, search results, playlists, and a single video itself

7 Dec 03, 2022
Python framework to scrape Pastebin pastes and analyze them

pastepwn - Paste-Scraping Python Framework Pastebin is a very helpful tool to store or rather share ascii encoded data online. In the world of OSINT,

Rico 105 Dec 29, 2022
Scrapes proxies and saves them to a text file

Proxy Scraper Scrapes proxies from https://proxyscrape.com and saves them to a file. Also has a customizable theme system Made by nell and Lamp

nell 2 Dec 22, 2021
This is python to scrape overview and reviews of companies from Glassdoor.

Data Scraping for Glassdoor This is python to scrape overview and reviews of companies from Glassdoor. Please use it carefully and follow the Terms of

Houping 5 Jun 23, 2022
Crawler in Python 3.7, 3.8. 3.9. Pypy3

Description Python Crawler written Python 3. (Supports major Python releases Python3.6, Python3.7 and Python 3.8) Installation and Use Setup VirtualEn

Vinit Kumar 2 Mar 12, 2022
Scrape all the media from an OnlyFans account - Updated regularly

Scrape all the media from an OnlyFans account - Updated regularly

CRIMINAL 3.2k Dec 29, 2022
A module for CME that spiders hashes across the domain with a given hash.

hash_spider A module for CME that spiders hashes across the domain with a given hash. Installation Simply copy hash_spider.py to your CME module folde

37 Sep 08, 2022
Current Antarctic large iceberg positions derived from ASCAT and OSCAT-2

Iceberg Locations Antarctic large iceberg positions derived from ASCAT and OSCAT-2. All data collected here are from the NASA SCP website Overview Thi

Joel Hanson 5 Jul 27, 2022