Analisando Conteúdo HTML com BeautifulSoup
Ao trabalhar com dados da web, você frequentemente encontrará respostas HTML. Para analisar HTML, a biblioteca BeautifulSoup do Python é uma excelente ferramenta. Nesta etapa, aprenderemos como extrair informações de respostas HTML.
Instalando BeautifulSoup
Primeiro, vamos instalar BeautifulSoup e seu analisador HTML:
pip install beautifulsoup4
Análise HTML Básica
Vamos criar um arquivo chamado parse_html.py para buscar e analisar uma página da web:
import requests
from bs4 import BeautifulSoup
## Make a request to a webpage
url = "https://www.example.com"
response = requests.get(url)
## Check if the request was successful
if response.status_code == 200:
## Parse the HTML content
soup = BeautifulSoup(response.text, 'html.parser')
## Extract the page title
title = soup.title.text
print(f"Page title: {title}")
## Extract all paragraphs
paragraphs = soup.find_all('p')
print(f"\nNumber of paragraphs: {len(paragraphs)}")
## Print the text of the first paragraph
if paragraphs:
print(f"\nFirst paragraph text: {paragraphs[0].text.strip()}")
## Extract all links
links = soup.find_all('a')
print(f"\nNumber of links: {len(links)}")
## Print the href attribute of the first link
if links:
print(f"First link href: {links[0].get('href')}")
else:
print(f"Request failed with status code: {response.status_code}")
Execute este script para ver como extrair informações básicas de uma página HTML:
python parse_html.py
Você deve ver a saída mostrando o título da página, o número de parágrafos, o texto do primeiro parágrafo, o número de links e a URL do primeiro link.
Encontrando Elementos Específicos
Agora, vamos ver como encontrar elementos específicos usando seletores CSS. Crie um arquivo chamado html_selectors.py:
import requests
from bs4 import BeautifulSoup
## Make a request to a webpage with more complex structure
url = "https://quotes.toscrape.com/"
response = requests.get(url)
## Check if the request was successful
if response.status_code == 200:
## Parse the HTML content
soup = BeautifulSoup(response.text, 'html.parser')
## Find all quote elements
quote_elements = soup.select('.quote')
print(f"Number of quotes found: {len(quote_elements)}")
## Process the first 3 quotes
print("\nFirst 3 quotes:")
for i, quote_element in enumerate(quote_elements[:3], 1):
## Extract the quote text
text = quote_element.select_one('.text').text
## Extract the author
author = quote_element.select_one('.author').text
## Extract the tags
tags = [tag.text for tag in quote_element.select('.tag')]
## Print the information
print(f"\nQuote #{i}")
print(f"Text: {text}")
print(f"Author: {author}")
print(f"Tags: {', '.join(tags)}")
else:
print(f"Request failed with status code: {response.status_code}")
Execute este script para ver como usar seletores CSS para extrair elementos específicos:
python html_selectors.py
Você deve ver a saída mostrando informações sobre as três primeiras citações, incluindo o texto da citação, o autor e as tags.
Construindo um Web Scraper Simples
Vamos juntar tudo para construir um web scraper simples que extrai dados estruturados de uma página da web. Crie um arquivo chamado quotes_scraper.py:
import requests
from bs4 import BeautifulSoup
import json
import os
def scrape_quotes_page(url):
## Make a request to the webpage
response = requests.get(url)
## Check if the request was successful
if response.status_code != 200:
print(f"Request failed with status code: {response.status_code}")
return None
## Parse the HTML content
soup = BeautifulSoup(response.text, 'html.parser')
## Extract all quotes
quotes = []
for quote_element in soup.select('.quote'):
## Extract the quote text
text = quote_element.select_one('.text').text.strip('"')
## Extract the author
author = quote_element.select_one('.author').text
## Extract the tags
tags = [tag.text for tag in quote_element.select('.tag')]
## Add the quote to our list
quotes.append({
'text': text,
'author': author,
'tags': tags
})
## Check if there's a next page
next_page = soup.select_one('.next a')
next_page_url = None
if next_page:
next_page_url = 'https://quotes.toscrape.com' + next_page['href']
return {
'quotes': quotes,
'next_page': next_page_url
}
## Scrape the first page
result = scrape_quotes_page('https://quotes.toscrape.com/')
if result:
## Print information about the quotes found
quotes = result['quotes']
print(f"Found {len(quotes)} quotes on the first page")
## Print the first 2 quotes
print("\nFirst 2 quotes:")
for i, quote in enumerate(quotes[:2], 1):
print(f"\nQuote #{i}")
print(f"Text: {quote['text']}")
print(f"Author: {quote['author']}")
print(f"Tags: {', '.join(quote['tags'])}")
## Save the quotes to a JSON file
output_dir = '/home/labex/project'
with open(os.path.join(output_dir, 'quotes.json'), 'w') as f:
json.dump(quotes, f, indent=2)
print(f"\nSaved {len(quotes)} quotes to {output_dir}/quotes.json")
## Print information about the next page
if result['next_page']:
print(f"\nNext page URL: {result['next_page']}")
else:
print("\nNo next page available")
Execute este script para extrair citações de um site:
python quotes_scraper.py
Você deve ver a saída mostrando informações sobre as citações encontradas na primeira página, e as citações serão salvas em um arquivo JSON chamado quotes.json.
Verifique o arquivo JSON para ver os dados estruturados:
cat quotes.json
O arquivo deve conter uma matriz JSON de objetos de citação, cada um com propriedades de texto, autor e tags.