Structured Data Extraction
Topic Overview
Hello and welcome! In this lesson, we'll be focusing on structured data extraction and storage. Specifically, we'll use Node.js, along with cheerio and csv-writer, to scrape data from web pages and store it in a CSV file. This process involves retrieving HTML content, parsing it to extract data, handling pagination, and finally saving the structured data.
Introduction to CSV Files
When scraping data from web pages, it's essential to store the extracted data in a structured format for further analysis. One common way to store structured data is by using a CSV (Comma-Separated Values) file. CSV files are easy to create, read, and share, making them a popular choice for storing tabular data. Here is an example of a CSV file:
csv-writer Library
csv-writer is a powerful library in Node.js for creating CSV files from structured data. It provides a simple and efficient way to write data to CSV files with customizable headers and formatting options. By using csv-writer, we can easily store structured data in a CSV file.
Here is an example of how to create structured data and save it to a CSV file using csv-writer:
After running this code, a CSV file named actors.csv will be created with the following content:
Now that we have an understanding of CSV files and the csv-writer library, let's move on to web scraping and data extraction.
Storing Scraped Data in a CSV File
In this code:
- We define the
extractToCSVfunction as an async function to handle the entire process.allQuotescollects all the quotes from all the pages.- We loop through each page, extract quotes in the format
{text: text, author: author, tags: tags}, and append them toallQuotes.
- We loop through each page, extract quotes in the format
- The loop is controlled by the
currentPagevariable, which is updated to the next page URL until there are no more pages.- The next page URL is extracted from the
.next aelement using cheerio'sattr('href')method.
- The next page URL is extracted from the
createCsvWriter()creates a CSV writer with the specified path and headers.csvWriter.writeRecords(allQuotes)saves the data to a CSV file.
The output of the above code will be the quotes.csv file containing the extracted data in a structured format.
Lesson Summary
In this lesson, we covered the process of extracting structured data from web pages and storing it in a CSV file. We used Node.js, cheerio, and csv-writer to scrape quotes from a website and save them in a CSV file.
Make sure to practice this on your own and explore other web scraping projects to enhance your skills. Happy coding!
