|
--- |
|
title: "Web Scraping mit Python: Bücher von Books to Scrape" |
|
author: "Dein Name" |
|
format: |
|
html: |
|
toc: true |
|
code-tools: true |
|
jupyter: python3 |
|
--- |
|
|
|
|
|
|
|
In diesem Tutorial lernen wir, wie man die Website [Books to Scrape](https://books.toscrape.com/) mit Python und `BeautifulSoup` scrapt. Diese Seite dient oft als Beispiel für Web-Scraping, da sie eine einfache Struktur hat und keine komplexen Schutzmaßnahmen gegen Scraping implementiert. |
|
|
|
|
|
|
|
Stellen Sie sicher, dass Sie die folgenden Python-Bibliotheken installiert haben: |
|
|
|
```bash |
|
pip install requests beautifulsoup4 pandas |
|
``` |
|
|
|
|
|
|
|
|
|
|
|
Zuerst verwenden wir die `requests`-Bibliothek, um den HTML-Inhalt der Seite abzurufen. |
|
|
|
```{python} |
|
import requests |
|
|
|
|
|
url = "https://books.toscrape.com/" |
|
|
|
|
|
response = requests.get(url) |
|
|
|
|
|
if response.status_code == 200: |
|
print("HTML-Inhalt erfolgreich abgerufen.") |
|
else: |
|
print(f"Fehler beim Abrufen der Seite: {response.status_code}") |
|
``` |
|
|
|
|
|
|
|
Jetzt parsen wir den abgerufenen HTML-Inhalt mit `BeautifulSoup`. |
|
|
|
```{python} |
|
from bs4 import BeautifulSoup |
|
|
|
|
|
soup = BeautifulSoup(response.text, 'html.parser') |
|
|
|
|
|
print(soup.title.string) |
|
``` |
|
|
|
|
|
|
|
Wir extrahieren nun die Titel und Preise der Bücher. |
|
|
|
```{python} |
|
|
|
book_titles = [] |
|
book_prices = [] |
|
|
|
|
|
books = soup.find_all('article', class_='product_pod') |
|
|
|
|
|
for book in books: |
|
title = book.h3.a['title'] |
|
price = book.find('p', class_='price_color').text |
|
book_titles.append(title) |
|
book_prices.append(price) |
|
|
|
|
|
for title, price in zip(book_titles, book_prices): |
|
print(f"{title}: {price}") |
|
``` |
|
|
|
|
|
|
|
Um die extrahierten Daten zu speichern, verwenden wir `pandas`, um sie in einem DataFrame zu organisieren. |
|
|
|
```{python} |
|
import pandas as pd |
|
|
|
|
|
books_df = pd.DataFrame({ |
|
'Title': book_titles, |
|
'Price': book_prices |
|
}) |
|
|
|
|
|
print(books_df.head()) |
|
``` |
|
|
|
|
|
|
|
In diesem Tutorial haben wir gelernt, wie man die Website [Books to Scrape](https://books.toscrape.com/) mit Python und `BeautifulSoup` scrapt. Wir haben die Titel und Preise der Bücher extrahiert und in einem DataFrame gespeichert. Dieses Beispiel kann als Grundlage für komplexere Scraping-Projekte dienen. |
|
|
|
|
|
|
|
- [BeautifulSoup-Dokumentation](https://www.crummy.com/software/BeautifulSoup/bs4/doc/) |
|
- [Requests-Dokumentation](https://docs.python-requests.org/en/latest/) |
|
- [Pandas-Dokumentation](https://pandas.pydata.org/docs/) |
|
|