Web Scraping with BeautifulSoup

Betul Mescioglu

Scraping a Children's Bedtime Story Website:

In this project, we will scrape a story website. This website offers 99 bedtime stories for children across five pages. Each story is presented with a thumbnail, title of the story along with a short description. The user can access the story by clicking the thumbnail. We will scrape the story titles along with the short descriptions; clean the text, if necessary, and display them in a neat list format. stories.jpg

#Import necessary libraries:
import pandas as pd
import requests
from bs4 import BeautifulSoup
import re

Since stories are displayed across 5 pages, we have to connect to the website 5 times. At each connection, we will add the content to a list called content_collect.

The website's address for the main page is "https://storiestogrowby.org/bedtime-stories-kids-free/". When users browse to the second page, the address becomes "https://storiestogrowby.org/bedtime-stories-kids-free/page/2". The address format is similar for the following pages. So, once we connect to the main page and collect the content, we can start a loop and go through pages two to five and collect content automatically.

#Create a list that will hold the content of all five pages:
content_collect = []
#Connect to the main page:
response = requests.get("https://storiestogrowby.org/bedtime-stories-kids-free/")
#Store the content of the main page
content = response.content
#Add content to content_collect:
content_collect.append(content)
#Do the same for pages 2 through 5 with a loop
for i in range(2,6):
    #Change the number at the end, to connect to the next page
    response = requests.get("https://storiestogrowby.org/bedtime-stories-kids-free/page/{}".format(i))
    #Get the content of the current page
    content = response.content
    #Add the current content to the list 
    content_collect.append(content)
#Print the size of the content list
print("The size of content_collect is {}.".format(len(content_collect)))
The size of content_collect is 5.

We see that the code above indeed collected the contents of five pages.

Now, we need to parse the html code. When we inspect the actual html file, we see that the story titles are stored under the class named "entry-title" and story descriptions are stored under the class named "entry-content". We will create a list called title to hold the story titles and another list called body to hold the short descriptions of the stories. Once we set up our parser using Beautiful Soup library, we will find all cases of "entry-title" and "entry-content" in the html code, and store the story title and short description of the story to the title and body lists respectively.

#Create a list to hold the names of the stories
title = []
#Create a list to hold the short descriptions of the stories
body =[]
#Go through each of 5 pages and parse the html code:
for i in range(5):
    parser = BeautifulSoup(content_collect[i], 'html.parser')
    #For each page, go through all the stories
    for j in range(len(parser.find_all(class_='entry-title'))):
        #For each story, add the name to the list title
        title.append(parser.find_all(class_='entry-title')[j].text)
        #For each story, add the description to the list body
        body.append(parser.find_all(class_='entry-content')[j].text)
print("First five stories' titles are:\n\n {}.\n".format(title[:5]))
print("First five stories' descriptions are:\n\n {}.".format(body[:5]))
First five stories' titles are:

 ['A Cinderella Story ~ Bedtime Stories for Kids', 'Snow White and the Seven Dwarfs Story ~ Bedtime Stories for Kids', 'Pinocchio Story ~ Fairy Tale Bedtime Stories in English for Kids', 'Beauty and the Beast Story Fairy Tale ~ Bedtime Story for Children', 'Rumpelstiltskin ~ A Fairy Tale Bedtime Story for Kids'].

First five stories' descriptions are:

 ['\nThe Classic fairytale of Cinderella: a young girl, mistreated by her step-mother and step-sisters, who finds out that dreams really can come true.\n', '\nThe Classic Fairytale Story of Snow White with a Modern Twist: Who is the “fair”est of them all? Snow White of course!\n', '\nA Bedtime Story of Honesty, Courage and Truth.\xa0 If Pinocchio is to become a Real boy he needs to learn how to be honest, brave and true.\n', '\nA Bedtime Story of Friendship and Love.\xa0 The Classic fairy tale of the youngest daughter Beauty and a monstrous Beast.\n', '\nA Grimm’s Brother Tale: A miller tells a tale that his daughter can turn straw into gold. A strange little man is willing to help…for a price. Guess his name and he will be gone…but what is his name?\n'].

We see that the data we collected need some cleaning.

We need only the titles of the stories but we see the titles of the stories are followed by a ~ sign and some redundant information. We will create a new list called title_new that will hold only the titles of the stories.

In the description part, we see many '\n's and '\xa0's that we have to get rid of to obtain a coherent story description. We will employ re library and write a regex to remove these from the text. Then we will add these descriptions of the stories to a new list called body_new.

#Create a list that will hold cleaned description 
body_new = []
#Create a list that will hold cleaned title
title_new = []
#Regex to get rid of uncoherent text
pattern=r"[\n\\']|\xa0"
#Go through all stories:
for k in range(len(body)):
    #Delete all '\n's and '\xa0's in the descriptions of the stories 
    body_new.append(re.sub(pattern, '', body[k]))
    #Store only the names of the stories, get rid of the second part
    title_new.append(title[k].split('~')[0])
print("First five stories' titles are:\n\n {}.\n".format(title_new[:5]))
print("First five stories' descriptions are:\n\n {}.".format(body_new[:5]))
First five stories' titles are:

 ['A Cinderella Story ', 'Snow White and the Seven Dwarfs Story ', 'Pinocchio Story ', 'Beauty and the Beast Story Fairy Tale ', 'Rumpelstiltskin '].

First five stories' descriptions are:

 ['The Classic fairytale of Cinderella: a young girl, mistreated by her step-mother and step-sisters, who finds out that dreams really can come true.', 'The Classic Fairytale Story of Snow White with a Modern Twist: Who is the “fair”est of them all? Snow White of course!', 'A Bedtime Story of Honesty, Courage and Truth. If Pinocchio is to become a Real boy he needs to learn how to be honest, brave and true.', 'A Bedtime Story of Friendship and Love. The Classic fairy tale of the youngest daughter Beauty and a monstrous Beast.', 'A Grimm’s Brother Tale: A miller tells a tale that his daughter can turn straw into gold. A strange little man is willing to help…for a price. Guess his name and he will be gone…but what is his name?'].

Now that we cleaned the data, we will display it in a presentable format.

We will create a dictionary to hold the data then use pandas library's DataFrame() function to lay out the data in a visually appealing way.

#Create a dictionary to hold 
#the titles and descriptions of the stories 
store_name_descr = {}
store_name_descr['Story Name'] = title_new 
store_name_descr['Short Description'] = body_new
#Create a DataFrame by using the dictionary
story_dataframe = pd.DataFrame(data=store_name_descr,  columns=['Story Name', 'Short Description'])
#Set the DataFrame so all text is left-aligned and index is hidden
pretty_story = story_dataframe.style.set_table_styles([dict(selector='th', props=[('text-align', 'left')])])
pretty_story.set_properties(**{'text-align': 'left'}).hide_index()
pretty_story
Story Name Short Description
A Cinderella Story The Classic fairytale of Cinderella: a young girl, mistreated by her step-mother and step-sisters, who finds out that dreams really can come true.
Snow White and the Seven Dwarfs Story The Classic Fairytale Story of Snow White with a Modern Twist: Who is the “fair”est of them all? Snow White of course!
Pinocchio Story A Bedtime Story of Honesty, Courage and Truth. If Pinocchio is to become a Real boy he needs to learn how to be honest, brave and true.
Beauty and the Beast Story Fairy Tale A Bedtime Story of Friendship and Love. The Classic fairy tale of the youngest daughter Beauty and a monstrous Beast.
Rumpelstiltskin A Grimm’s Brother Tale: A miller tells a tale that his daughter can turn straw into gold. A strange little man is willing to help…for a price. Guess his name and he will be gone…but what is his name?
Goldilocks and the Three Bears Goldilocks and the Three Bears ~ Bedtime Stories for Kids. Goldilocks finds the three bears cottage in the woods. Should she make herself comfortable?
Hansel and Gretel Hansel and Gretel Bedtime Stories for Kids. When Hansel and Gretel go in search of food, they find a gingerbread house. But who is inside?
Rapunzel by the Brothers Grimm A Story of Friendship, Love and Courage. Rapunzel’s Story ~ A Brothers Grimm Fairy Tale. An evil witch has trapped Rapunzel in a tower. Can her long hair or love save her?
The Sword in the Stone: a King Arthur Legend of the Sword Story A Story of Courage, Justice and Self-Awareness. Merlin the Magician places a magic sword in a stone…whomever can pull it out is the rightful king.
The Ugly Duckling Story A Bedtime Story of Acceptance and Self-Awareness. A Mama Duck is proud when her six ducklings hatch from their eggs. But one duckling does not look like the others? Is he truly an Ugly Duckling?
The Frog Prince: The Story of the Princess and the Frog The classic Brother’s Grimm fairytale that sparked the Disney adaptation.
The Little Mermaid Story A Story of Courage, Learning and Love.The Classic fairy tale: The Little Mermaid falls in love with a prince on shore and she makes a deal with the Sea Witch to become human. But without her voice, how can the prince fall in love with her?
Aladdin and the Magic Lamp from The Arabian Nights This Classic Folktale is adapted from the original story of “Aladdin” from The Arabian Nights. Aladdin, the Genie and the Magic Lamp work to impress the princess who wishes to be a commoner.
Bambi Story: A Life in the Woods A Story of Courage, Kindness to Animals and Learning. The Classic Tale of a male deer, Bambi, his mother and his adventures learning in the woods.
Robin Hood and the Golden Arrow Story A Story of Charity, Compassion and Justice, from England.Robin Hood takes part in an archery contest thrown by the Sheriff of Nottingham. Will he realize its a trap before it is too late? One of the many Tales of Robin Hood.
Maui from Moana: Tales of the Demi-God This is the Legend Tale of Maui the Demi-God from Moana. It is part of our Classic Bedtime Stories for Kids Collection. It has been adapted from the Tales of Maui as well as Disney’s version of Moana.
The Velveteen Rabbit Story A Bedtime Story in Simple English for Kids. A toy rabbit learns that through a child’s love it can become real.
The Snow Queen Fairy Tale Story The Classic Tale of the Snow Queen: Gerda and Kai struggle to fight the Snow Queen and find the balance between Good and Evil.
Sleeping Beauty Fairy Tale Story The Classic Fairy Tale of Sleeping Beauty. Princess Aurora has been cursed by Maleficent. When she pricks herself on a spinning wheel on her 16th birthday, she is put into a deep sleep for 100 years. Who can save her?
The Gift of the Magi Story Bedtime Story for Kids: The Gift of the Magi, A Christmas Story. Della and Jim wish to give each other the perfect Christmas present, but how will they come up with the money?
Pocahontas and John Smith Story A Bedtime Story of Friendship, Courage and Acceptance. . The story tells of the time Pocahontas saved the life of settler John Smith from her father, Powhatan.
The Emperor’s New Clothes Story A Bedtime Story in Simple English for Kids. The Emperor is fooled into believing he is wearing magic clothes which can’t be “seen”.
Mulan Story A Bedtime Story in Simple English for Kids. Based on the “Ballad of Mulan” and Disney’s Mulan, this is a legend tale about a girl who goes in disguise as a boy and joins the army in her brother’s place.
Is There Anyone Like Me? A donkey wonders if there is anyone in the world just like him.
Short Stories for Kids […]
The Girl Who Changed Her Fate Poor Alena is cursed with an ill fate. Is there a way for her to change it?
The Girl with the Loveliest Hair in the World A Story of Love from Pakistan.A prince sets out to discover why every night his bride, the girl with the loveliest hair in the world, returns home.
The Girl Fish A girl is transformed into a fish to seek the lost crown of a queen-fish.
The Little Boy and Girl in the Clouds, The Tale of El Capitan Overnight, a magic rock, El Capitan, raises a boy and girl who had fallen asleep on top of it.
The Girl and the Puma A frightened Spanish girl forges a powerful relationship with a puma.
The Maiden and the Boy who Vanished Three maidens try to rescue a nobleman’s son who had vanished.
How to Turn Dirt Into Gold A young man learns the secret of how to turn dirt into gold.
A Caterpillar’s Voice Who is in the hare’s cave? A big voice!
A Donkey to Market A Bedtime Story in Simple English for Kids. How to best take their donkey to market? Everyone weighs in.
The Painting & the Cat Fable Short Stories for Kids: The fable is a fictional story meant to teach a moral lesson. See what lesson about the nature of perception Mark Twain is trying to show us.
Androcles and the Lion Androcles, an escaped slave, meets a lion in the woods. An Aesop’s tale.
A Spider & Robert the Bruce An English Story for Kids Learning to Read. A defeated Scottish king, Robert the Bruce, is inspired by a spider. (from Scotland)
A Story from Confucius on Losing One’s Temper Story from Confucius: Folktale story for kids from the philosopher Confucius which explains losing one’s temper and the art of self-control.
A Surprise in the Oven Story A story of creative thinking and working together from Canada.
Akbar and the Half-Reward An English Story for Kids Learning to Read. Akbar gives a reward to Mahesh Das who saved him but someone else demands half. What will he do when he is bullied to split the reward?
All for a Paisa Story A father challenges his son to solve an impossible riddle with only a paisa.
Birbal and the Mango Tree An English Story for Kids Learning to Read. Who owns the Mango tree? Birbal helps two men decide and discover who is the proper owner.
Birbal Finds a Thief An English Story for Kids Learning to Read. How can Birbal tell who the thief is? With a clever plan, of course!
Haku’s Power Haku yearns to be Emperor- if only!
Little Ant’s Big Plan by Book Dash Little Ant loves to read but should be gathering food instead. Can a book help him do both?
Sima Guang Breaks the Vat A Chinese Story in English for Kids Learning to Read. Sima Guang is tasked to save his friend who has fallen in a vat of water.
Swapping Places A farmer and his wife swap places, and he finds her work is not so easy.
The Apple Dumpling Story A Bedtime Story in Simple English for Kids. An old woman’s search for an apple dumpling leads her to generous trades. A story of Gratitude and Kindness.
The Bear Feast Story A Story of Friendship, Hospitality and Sharing, from the United States.An old man invites the grizzly bear chief and his followers to a feast.
The Empty Pot An English Story for Kids Learning to Read. The boy who grows the finest plant will be emperor, but Jun’s seed does not sprout.
The Enormous Turnip An old man grows a giant turnip. A Russian folktale.
The Geese and the Fig Tree Panchatantra Stories: When a vine starts to grow, the wise geese says to get rid of it. What happens when something small becomes a big problem?
The Great Fire Story A great fire wipes out all peoples on earth except two.
The Man, the Hawk & the Dove A man is torn between two warring animals, and their tempting pleas.
The Mice and the Elephants Panchatantra Stories: A herd of elephants do a favor for the mice. How can a small thing repay a big thing? A story of Helping.
The Poor Farmer’s Wish: The Tale of the Silver on the Hearth A poor farmer finds a jar of coins and leaves them behind because they are not his.
The Story of the Aged Mother by Matsuo Basho Folktale Stories for Kids: this Japanese folktale tells the story of an unkind ruler who issues cruel orders, including a demand that all old folks are to be abandoned and left to die. Basho tells a poignant story about a mother and her son and their love for one another.
The Tsar’s Daughter A Tsar’s daughter battles a monster to prove to her father she can rule.
The Wise Young Girl Becomes Head of the Household To be allowed back home, three brides must find rare and impossible items. A young, wise girl is eager to help.
Two Brothers Story A Folktale Story of Brotherly Love from Israel.A rare folk tale about the love and generosity of two brothers. This tale has both Hebrew and Arab derivation.
Weighing the Elephant A Chinese Riddle Tale in English for Kids Learning to Read.A Chinese king is amazed by the gift of an elephant- but how to weigh it?
White Wing: The Tale of the Doves and the Hunter Panchatantra Stories: A Hunter puts a net on the banyan tree. Can the doves escape? A story of Teamwork.
Yuuki and the Tsunami A boy saves 400 villagers from a sudden tsunami. True story.
Beauty and the Beast Classic Tale Classic fairy tale of a plucky youngest daughter Beauty and a monstrous beast.
The Beekeeper and the Bewitched Hare A beekeeper must protect an enchanted hare from an evil witch.
Boots and His Brothers Three brothers embark on a quest to serve their King.
The Enormous Nose Flatterers divert the Prince from the truth about his enormous nose. (from France)
The Fisherlad & the Mermaid’s Ring A fisherlad wins a mermaid’s ring to win the heart of his own true love.
The Frog & the Condor A girl kept as a slave by a condor is offered a hope of rescue.
Goblin’s Market, A Halloween Poem The goblins have captured Sarah. To save Sarah, what must her sister do?
The Golden Goose A parade of villagers get stuck to Simpleton and his golden goose.
Time Changes All Things: Greyfoot and the Princess of England A haughty princess must marry a beggar, who is actually a prince in disguise.
Guleesh and the Princess of France After Guleesh and his band kidnap a princess, he tries to make amends.
Janet and Thomalyn (Tamlane) Only Janet can save Thomalyn from being sacrificed by the Fairies.
Princess Kate Story Princess Kate and her sister flee the palace to try to break an evil spell.
The Lad and the Maiden in the Rose-Colored Clouds A Story of Courage, Friendship and Love, from Scotland.A lad spends his life searching for a maiden who appeared in his dream.
The Lion’s Enchantment To save a prince, a maiden must give up what is most valuable to her.
The Witch’s Magic Ball A Story of Cooperation and Perseverance, from Argentina.An evil witch lures a girl with a magic ball, and her brother must free her.
The Magic Horse A prince jumps on a magic horse without first hearing how to run it.
The Magic Mirror The King will marry only a maiden who will look into his magic mirror.
The Magic Tree Trunks A prince and princess exiled from the castle hide in two magic tree trunks.
The Native American Cinderella Story from Canada A scar-faced youngest of three daughters seeks a warrior’s heart.
Princess Amaradevi Story Princess Amaradevi engineers a scheme to free her exiled husband.
Prince Derek and the Ring Prince Derek throws off the magic ring designed to help him stay good.
Queen Anait Anait will marry the the prince only if he first learns a trade.
The Queen and the Mouse Fairy Tale A queen locked up as prisoner has but one friend- a dancing mouse.
Rags and Tatters Whoever picks up a rose thrown into the street will marry the princess.
The Contest of the Fairies (Fairy) Two fairies bet on whether a womanizing prince will stay true. (from France)
The Six Friends One of six friends is missing – where is he? The five friends go in search.
The Spellbook in the Forbidden Room A spellbook holds the key to rescue- but who can read the spells?
The Stolen Bairn (Baby) A Scottish folk tale of a mother’s fierce love for her baby (“bairn”).
Sunlight & Moonlight Two young princes escape danger at the palace, & find more in the desert.
Susu and the Magic Mirror Susu’s magic mirror reveals the truth about her stepmother.
The Talking Eggs The talking eggs of a magical old woman can bring fortunes- or not.
The Golden Goats Three brothers catch runaway golden goats, but not for long.
The Troll in the Ditch A Story of Generosity, Helping, and Selflessness, from Sweden.Pedar is rushing to get to Lisa’s house- why take time to help a little old troll in a ditch?
The Twelve Wild Ducks A princess risks everything to free her 12 older brothers from a spell.
The Wild Man & the Prince Exiled, a prince is forced by his servant to switch clothes.
Baba Yaga the Russian Witch Baba Yaga: A classic Russian Fairytale in Early Reader version. Natasha is sent deep into the forest to face the witch, Baba Yaga.

Pandas' DataFrame() is an incredibly dynamic and useful tool to hold data. We can sort, retrieve, delete or filter data very easily by using dataframes as they are an integral part of the Python and Numpy ecosystems.

In this project, we scraped a website, captured the necessary parts of the data, cleaned and presented it in a user friendly way.

Made with REPL Notes Build your own website in minutes with Jupyter notebooks.