Home Backend Development Python Tutorial How to Scrape Data From Goodreads Using Python and BeautifulSoup

How to Scrape Data From Goodreads Using Python and BeautifulSoup

Dec 10, 2024 am 10:40 AM

Web scraping is a powerful tool for gathering data from websites. Whether you’re collecting product reviews, tracking prices, or, in our case, scraping Goodreads books, web scraping provides endless opportunities for data-driven applications.

In this blog post, we’ll explore the fundamentals of web scraping, the power of the Python BeautifulSoup library, and break down a Python script designed to scrape Goodreads Choice Awards data. Finally, we’ll discuss how to store this data in a CSV file for further analysis or applications.


What is Goodreads?

Goodreads is the world’s largest platform for readers and book recommendations. It provides users with access to book reviews, author details, and popular rankings. Every year, Goodreads hosts the Goodreads Choice Awards, where readers vote for their favorite books across various genres like fiction, fantasy, romance, and more. This makes Goodreads an ideal target for web scraping to gather insights about trending books and authors.


What is Web Scraping?

Web scraping involves extracting data from websites in an automated manner. It allows you to collect and structure information for tasks such as:

  • Analyzing trends and patterns.
  • Aggregating content like reviews or articles.
  • Feeding machine learning models or databases.

Setting Up Your Environment

Before diving into the script, you need to install the necessary libraries.

  1. Install Python

    Make sure you have Python installed on your system.

  2. Install Required Libraries

    Install the required libraries using pip:

    pip install beautifulsoup4
    pip install requests
    
    Copy after login
    Copy after login
    Copy after login

    request: Allows us to send HTTP requests to a URL and retrieve the web page’s content.

    BeautifulSoup: Simplifies HTML parsing and data extraction.

Once these installations are complete, you're ready to scraping!


Introduction to BeautifulSoup

BeautifulSoup is a Python library for parsing HTML and XML documents. It enables developers to navigate page structures, extract content, and transform raw HTML into a structured format.

Key Methods in BeautifulSoup

Here are a few essential methods that we will be using in our script:

  • BeautifulSoup(html, 'html.parser'): Initializes the parser and allows you to work with the HTML content.
  • soup.select(selector): Finds elements using CSS selectors, such as classes or tags.
  • soup.find(class_='class_name'): Locates the first occurrence of an element with a specified class.
  • soup.find_parent(class_='class_name'): Finds the parent tag of the current element.
  • soup.get('attribute'): Retrieves the value of an attribute from an element, like href or src.

For a complete list of methods, check out the BeautifulSoup documentation.


Setting Up the Script

Let’s begin by importing the necessary libraries and defining custom headers to mimic a browser. This helps avoid getting blocked by the website.

pip install beautifulsoup4
pip install requests
Copy after login
Copy after login
Copy after login

Scraping Categories and Books

We start by defining the URLs for Goodreads’ Choice Awards page and the main application. We will send a request to start_url and get the web page's content.

from bs4 import BeautifulSoup as bs
import requests
import re
import csv

HEADERS = {
    "User-Agent": "Mozilla/5.0 (X11; Linux x86_64)...",
    "Accept-Language": "en-US, en;q=0.5",
}
Copy after login
Copy after login

Each category contains a genre and a link to its respective page. Using soup.select, we extract all categories listed under the .category class.

How to Scrape Data From Goodreads Using Python and BeautifulSoup

Next, iterate through each category to get the genre name and its page URL.

app_url = "https://www.goodreads.com"
start_url = "https://www.goodreads.com/choiceawards/best-books-2024"

res = requests.get(start_url, headers=HEADERS)
soup = bs(res.text, 'html.parser')

categories = soup.select('.category')
Copy after login
Copy after login

Here, we extract the category name (genre) and the category page URL for further processing.

We will send another request to each category_url and locate all the books under that category.

for index, category in enumerate(categories):
    genre = category.select('h4.category__copy')[0].text.strip()
    url = category.select('a')[0].get('href')
    category_url = f"{app_url}{url}"
Copy after login
Copy after login

category_books will contain the list of all the books under the respective category.

Extracting Book Data

Once we have the list of books, we will be iterating over each books and extract the data.

Extract Votes

res = requests.get(category_url, headers=HEADERS)
soup = bs(res.text, 'html.parser')

category_books = soup.select('.resultShown a.pollAnswer__bookLink')
Copy after login
Copy after login

If we see in the DOM, voting count is present in the parent element of the category element. So we need to use find_parent method to locate the element and extract the voting count.

How to Scrape Data From Goodreads Using Python and BeautifulSoup

Extract Book Title, Author and Image URL

for book_index, book in enumerate(category_books):
    parent_tag = book.find_parent(class_='resultShown')
    votes = parent_tag.find(class_='result').text.strip()
    book_votes = clean_string(votes).split(" ")[0].replace(",", "")
Copy after login

Each book's URL, cover image URL, title and author are extracted.

The clean_string function ensures the title is neatly formatted. You can define it at the top of the script

book_url = book.get('href')
book_url_formatted = f"{app_url}{book_url}"
book_img = book.find('img')
book_img_url = book_img.get('src')
book_img_alt = book_img.get('alt')
book_title = clean_string(book_img_alt)
print(book_title)
book_name = book_title.split('by')[0].strip()
book_author = book_title.split('by')[1].strip()
Copy after login

Extract More Book Details

To get more details about the book like rating, reviews, etc., we will be sending another request to book_url_formatted.

def clean_string(string):
    cleaned = re.sub(r'\s+', ' ', string).strip()
    return cleaned
Copy after login

Here get_ratings_reviews returns the ratings and reviews text well formatted.

How to Scrape Data From Goodreads Using Python and BeautifulSoup

You can define this function at the top of the script.

pip install beautifulsoup4
pip install requests
Copy after login
Copy after login
Copy after login

By navigating to each book’s details page, additional information like ratings, reviews, and detailed descriptions is extracted. Here, we are also checking if book description element exists otherwise putting a default description so that the script does not fails.

from bs4 import BeautifulSoup as bs
import requests
import re
import csv

HEADERS = {
    "User-Agent": "Mozilla/5.0 (X11; Linux x86_64)...",
    "Accept-Language": "en-US, en;q=0.5",
}
Copy after login
Copy after login

Here, we have also gathered author details, publication information and other metadata.

Create a Book Dictionary

Let's store all the data we have extracted for a book in a dictionary.

app_url = "https://www.goodreads.com"
start_url = "https://www.goodreads.com/choiceawards/best-books-2024"

res = requests.get(start_url, headers=HEADERS)
soup = bs(res.text, 'html.parser')

categories = soup.select('.category')
Copy after login
Copy after login

We will use this dictionary to add the data in a csv file.


Storing Data in a CSV File

We will use the csv module which is a part of Python's standard library. So you don't need to install it separately.

First we need to check if this is the first entry. This check is required to add the header in the csv file in the first row.

for index, category in enumerate(categories):
    genre = category.select('h4.category__copy')[0].text.strip()
    url = category.select('a')[0].get('href')
    category_url = f"{app_url}{url}"
Copy after login
Copy after login

We are using mode="w" which will create a new csv file with the header entry.

Now for all subsequent entries, we will append the data to the CSV file:

res = requests.get(category_url, headers=HEADERS)
soup = bs(res.text, 'html.parser')

category_books = soup.select('.resultShown a.pollAnswer__bookLink')
Copy after login
Copy after login

mode="a" will append the data to CSV file.

Now, sit back, relax, and enjoy a cup of coffee ☕️ while the script runs.

Once it’s done, the final data will look like this:

How to Scrape Data From Goodreads Using Python and BeautifulSoup

You can find the complete source code in this github repository.


Summary

We have learned how to scrape Goodreads data using Python and BeautifulSoup. Starting from basic setup to storing data in a CSV file, we explored every aspect of the scraping process. The scraped data can be used for:

  • Data visualization (e.g., most popular genres or authors).
  • Machine learning models to predict book popularity.
  • Building personal book recommendation systems.

Web scraping opens up possibilities for creative data analysis and applications. With libraries like BeautifulSoup, even complex scraping tasks become manageable. Just remember to follow ethical practices and respect the website’s terms of service while scraping!

The above is the detailed content of How to Scrape Data From Goodreads Using Python and BeautifulSoup. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1659
14
PHP Tutorial
1258
29
C# Tutorial
1232
24
Python vs. C  : Applications and Use Cases Compared Python vs. C : Applications and Use Cases Compared Apr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

How Much Python Can You Learn in 2 Hours? How Much Python Can You Learn in 2 Hours? Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

See all articles