0% found this document useful (0 votes)
29 views5 pages

Scraping Inspirational Quotes with Python

This document provides a guide on how to scrape inspirational quotes from the website goodreads.com using Python. It explains the concept of web scraping, the structure of the target website, and includes a detailed programming example using BeautifulSoup and requests libraries. The article concludes by encouraging readers to explore further resources on Python programming.

Uploaded by

Tharaka Gaddam
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views5 pages

Scraping Inspirational Quotes with Python

This document provides a guide on how to scrape inspirational quotes from the website goodreads.com using Python. It explains the concept of web scraping, the structure of the target website, and includes a detailed programming example using BeautifulSoup and requests libraries. The article concludes by encouraging readers to explore further resources on Python programming.

Uploaded by

Tharaka Gaddam
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

WEB SCRAPING IN PYTHON:

mmmmmmmmmmmmmmmmmkmmmmmmmmmmmmmmmmmmmmmkmWEB SCRAPE ON
INSPIRATIONAL QUOTES USING PYTHON:

{HOW TO SCRAPE INSPIRING QUOTES FROM THE INTERNET WITH PYTHON}

In this article, I will show you how to scrape inspirational quotes from a website using the Python
programming language. I think everyone likes to hear some inspirational quotes from time to time
and hopefully the quotes that we will scrape within this article will brighten your day.

For anyone reading this article and don’t know what web scraping is, I will define it now. Web
scraping, or simply scraping is the act or process of extracting data from a website. This means you
will learn how to extract information from a website using Python.

Understanding the Concept Before Writing the Program


Before writing any code, we must first understand the concept and method for scraping the website.
We have to find a website that contains inspirational quotes. Once, that site is found, then we need
to understand how that website is structured to find and extract the quote data that we want.

1. Find A Website That Contains Inspirational Quotes


Like I said before, we need to find a website that contains the data that we want to extract. Luckily, I
was able to find a great website called [Link]. The link is
[Link] This website contains inspirational
quotes, and the author who is being quoted.
2. View The Structure Of The Website
Now, we need to know how this website is structured. This can be done by using the inspection tool
on the Google Chrome Browser.

By using the inspection tool, I can see that the quotes appear to be under the div tag with class =
“quoteText”, and the author of the quote is under the span tag with class = “authorOrTitle” ,so I will
use this information to help me gather the data.
Furthermore, I can see that those two classes are under other div tags. So this information will help
me locate these two classes that contain the data that I want through the program. Also the site
itself has many pages with quotes, so this means I can iterate through each page to gather more
quotes simply by changing the page number at the end of the URL.

Example of iterating through the web page:


[Link]
[Link]

[Link]

If you prefer not to read this article and would like a video representation of it, you can check out the
YouTube Video . It goes through everything in this article with a little more detail, and will help make
it easy for you to start programming even if you don’t have the programming language Python
installed on your computer. Or you can use both as supplementary materials for learning.

Programming
First I will write a description about the program, this way I can simply read the description and know
what this program is about or is supposed to do.

#Description: Scrape Inspirational Quotes Using Python

Next, I want to import the libraries that are needed throughout the program

#Import the dependencies

from bs4 import BeautifulSoup


import pandas as pd

import requests

import [Link]

import time

Now, create empty lists to store the inspirational quote and the author of the quote.

#Create lists to store the scraped data

authors = []

quotes = []

Time for the “meat” of the program. I will create a function to automatically scrape the quote and
the author of the quote and store that data into the empty lists created previously.

#Create a function to scrape the site

def scrape_website(page_number):

page_num = str(page_number) #Convert the page number to a string

URL = '[Link] #append the page


number to complete the URL

webpage = [Link](URL) #Make a request to the website

soup = BeautifulSoup([Link], "[Link]") #Parse the text from the website

quoteText = soup.find_all('div', attrs={'class':'quoteText'}) #Get the tag and it's class

for i in quoteText:

quote = [Link]().split('\n')[0]#Get the text of the current quote, but only the sentence before a
new line

author = [Link]('span', attrs={'class':'authorOrTitle'}).[Link]()

#print(quote)

[Link](quote)

#print(author)

aLoop through ’n’ number of pages to scrape the quotes from.

#Loop through 'n' pages

n = 10

for num in range(0,n):

scrape_website(num)
Combine the two lists [Link](author)

#Combine the lists

combined_list = []

for i in range(len(quotes)):

combined_list.append(quotes[i]+'-'+authors[i])

Finally, time to show the inspirational quotes and the author of that quote!

#Show the combined list

combined_list

That’s it, you are done! Hopefully this was useful to you!

If you are interested in reading more on Python one of the fastest growing programming languages
that many companies and computer science departments use, then I recommend you check out the
book Learning Python written by Mark Lutz’s.

Conclusion
Thanks for reading this article I hope its helpful to you all! If you enjoyed this article and found it
helpful please leave a comment to show your appreciation. Keep up the learning, and if you like
machine learning, mathematics, computer science, programming or algorithm analysis, please visit
and subscribe to my YouTube channels (randerson112358 & computer science).

Common questions

Powered by AI

Iterative processes in URLs allow for the scraping of multiple pages by systematically altering URL parameters, such as page numbers. For the given project, the URL pattern 'https://www.goodreads.com/quotes/tag/inspirational?page=X' is identified, where 'X' represents the page number. A loop in the scraping script can increment this page number parameter to access additional pages. By automating the variable page number within the loop, it becomes possible to scrape sequential pages efficiently, collecting a larger dataset from the website without manually visiting each page .

Preparation for Python web scraping involves understanding the goal of the scraping project, identifying a target website, and inspecting its HTML structure to locate where the needed data resides. Using browser developer tools helps reveal the site's structure, identifying specific tags and classes where data is located. Setting up the Python environment by installing necessary libraries like BeautifulSoup and requests is essential. Creating lists or datasets to store the extracted data organizes the collection process. A well-structured planning phase helps streamline the coding process to target and extract required data efficiently .

Challenges and ethical considerations in web scraping include legal issues, website terms of service violations, and potential impacts on website performance. Some websites may explicitly disallow scraping in their robots.txt file, creating legal boundaries. Scraping must respect these terms to avoid potential litigation. Additionally, excessive scraping can impose a significant load on a website's server, affecting its performance and accessibility for others. Ethical scraping practices involve respecting the website's terms of use, minimizing server load, and ensuring data is used responsibly, especially regarding personal information .

Converting the page number to a string is necessary when constructing dynamic URLs because URLs are strings by nature. When concatenating components to form a complete URL, every part must be a string. If the page number remains in an integer format, it would result in an error during string concatenation operations. By converting it to a string, it seamlessly integrates with the rest of the URL string, allowing the program to cycle through URLs associated with different pages for scraping purposes .

Web scraping involves programmatically extracting data from websites, in this case, inspirational quotes. The process begins with identifying a suitable website, such as goodreads.com, which contains the desired data. By inspecting the website's HTML structure using tools like the Chrome inspection tool, the class locations of quotes and authors can be determined. Quotes are located under the div tag with class 'quoteText' and authors under the span tag with class 'authorOrTitle'. These elements are iterated over to extract and store the data. This is achieved using Python libraries such as BeautifulSoup for parsing HTML, and modules like requests for HTTP requests to access page content, enabling automated data extraction across multiple pages by altering the page number in URLs .

Effective data storage and organization are critical for managing the information collected during web scraping. Storing data in lists, as shown in the project, allows for orderly accumulation of quotes and authors, which can later be manipulated or analyzed. Proper organization facilitates easy combination of datasets and conversion into structured formats, such as dataframes, which enhance data manipulation capabilities, visualization, and further analysis. This organization ensures the scalability of the scraping project by maintaining clarity and accessibility as the data volume increases, supporting various post-processing activities .

Functions in a web scraping project encapsulate repetitive tasks, making code more organized, reusable, and easier to maintain. Using a function to handle scraping logic allows it to be called multiple times with different parameters, such as page numbers, enabling systematic data extraction across numerous pages. Functions improve readability by abstracting complex procedures and preventing code duplication. They also simplify debugging and modifications as any change affects all instances where the function is invoked, facilitating consistency and efficiency in handling large volumes of data .

The BeautifulSoup library is used for parsing HTML documents, which is essential for web scraping tasks. It allows developers to navigate the HTML tree structure and search for specific tags and attributes where data resides. Using methods like find_all or find, BeautifulSoup can isolate elements defined by specific classes or IDs, extract text from them, and clean or format that data as required. This makes it a powerful tool for efficiently dissecting webpage content to extract only the desired elements, such as quotes and authors in this context, from the HTML markup .

Crucial elements for locating specific data in web scraping include HTML tags and their associated attributes like class names. Identifying these structures involves using inspection tools, such as the Chrome Developer Tools, which allow users to navigate through the HTML hierarchy. Elements of interest might be encapsulated in div tags with specific class names indicating data segments, like 'quoteText' for quotes and 'authorOrTitle' for authors. By honing in on these specific attributes and understanding the overall layout of the webpage in the DOM, scrapers can accurately target the data elements they are tasked with extracting .

Essential Python libraries for web scraping include BeautifulSoup, requests, and optionally pandas. BeautifulSoup is used to parse HTML documents, making it easy to locate and extract data from specific tags and attributes. The requests module is utilized to send HTTP requests to access website content that needs to be scraped. Additionally, pandas can be employed to organize and manipulate data into structured formats like dataframes if needed. Together, these libraries create a streamlined process where requests fetch the URL content, BeautifulSoup parses the HTML to find and extract the targeted elements, and the organized data is stored, often for further processing or analysis .

You might also like