Parsen von HTML-Inhalten mit BeautifulSoup
Bei der Arbeit mit Webdaten werden Sie oft auf HTML-Antworten stoßen. Für das Parsen von HTML ist die Python-Bibliothek BeautifulSoup ein hervorragendes Werkzeug. In diesem Schritt lernen wir, wie man Informationen aus HTML-Antworten extrahiert.
Installieren von BeautifulSoup
Zuerst installieren wir BeautifulSoup und seinen HTML-Parser:
pip install beautifulsoup4
Grundlegendes HTML-Parsen
Erstellen wir eine Datei namens parse_html.py, um eine Webseite abzurufen und zu parsen:
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}")
Führen Sie dieses Skript aus, um zu sehen, wie man grundlegende Informationen von einer HTML-Seite extrahiert:
python parse_html.py
Sie sollten eine Ausgabe sehen, die den Seitentitel, die Anzahl der Absätze, den Text des ersten Absatzes, die Anzahl der Links und die URL des ersten Links anzeigt.
Finden bestimmter Elemente
Sehen wir uns nun an, wie man bestimmte Elemente mit CSS-Selektoren findet. Erstellen Sie eine Datei namens 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}")
Führen Sie dieses Skript aus, um zu sehen, wie man CSS-Selektoren verwendet, um bestimmte Elemente zu extrahieren:
python html_selectors.py
Sie sollten eine Ausgabe sehen, die Informationen über die ersten drei Zitate anzeigt, einschließlich des Zitattests, des Autors und der Tags.
Erstellen eines einfachen Web Scrapers
Lassen Sie uns alles zusammenfügen, um einen einfachen Web-Scraper zu erstellen, der strukturierte Daten von einer Webseite extrahiert. Erstellen Sie eine Datei namens 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")
Führen Sie dieses Skript aus, um Zitate von einer Website zu scrapen:
python quotes_scraper.py
Sie sollten eine Ausgabe sehen, die Informationen über die auf der ersten Seite gefundenen Zitate anzeigt, und die Zitate werden in einer JSON-Datei namens quotes.json gespeichert.
Überprüfen Sie die JSON-Datei, um die strukturierten Daten zu sehen:
cat quotes.json
Die Datei sollte ein JSON-Array von Zitatobjekten enthalten, jedes mit den Eigenschaften Text, Autor und Tags.