IMDB = Internet Movie Data Base
IMDB.com is a renowned online database dedicated to cataloging information about movies, TV shows, and celebrities. Established in 1990, IMDb is now under the ownership of Amazon. The platform is highly regarded for its extensive offerings, encompassing film and TV show ratings, user reviews, trailers, detailed cast and crew information, as well as the latest industry news.
In this context, we will embark on scraping data related to horror movies from IMDb, utilizing the ‘rvest’ package in R.
Our goal is to extract information on horror films and the cast associated with them.
# Install Libraries and once installed comment out
#install.packages("tidyverse")
#install.packages("rvest")
Both tidyverse and rvest are powerful tools
that can greatly assist in various aspects of data analysis and web
scraping within the R programming environment.
# Load the libraries
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr 1.1.2 ✔ readr 2.1.4
## ✔ forcats 1.0.0 ✔ stringr 1.5.0
## ✔ ggplot2 3.4.2 ✔ tibble 3.2.1
## ✔ lubridate 1.9.3 ✔ tidyr 1.3.0
## ✔ purrr 1.0.1
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(rvest)
##
## Attaching package: 'rvest'
##
## The following object is masked from 'package:readr':
##
## guess_encoding
I like to change the genres around…. here I’ve changed it to horror
# Read the link
link = "https://www.imdb.com/search/title/?genres=horror&sort=user_rating,desc&title_type=feature&num_votes=30000,&pf_rd_m=A2FGELUUNOQJNL&pf_rd_p=f11158cc-b50b-4c4d-b0a2-40b32863395b&pf_rd_r=GMJM46PTFY8D7B4S5199&pf_rd_s=right-6&pf_rd_t=15506&pf_rd_i=top&ref_=chttp_gnr_1"
page = read_html(link)
Extract the specific fields and their values
# Extract from fields: name, year, genre, length, user rating, director and synopsis
name<-page%>%html_nodes(".lister-item-header a")%>%html_text()
year<-page%>%html_nodes(".text-muted.unbold")%>%html_text()
genre<-page%>%html_nodes(".genre")%>%html_text()
genre <- gsub("\n", " ", genre) # to remove \n
length<-page%>%html_nodes(".runtime")%>%html_text()
user_rating<-page%>%html_nodes(".ratings-imdb-rating strong")%>%html_text()
director<-page%>%html_nodes(".text-muted+ p a:nth-child(1)")%>%html_text()
synopsis<-page%>%html_nodes(".ratings-bar+ .text-muted")%>%html_text()
synopsis <- gsub("\n", " ", synopsis) # to remove \n
# convert to df
library(knitr)
# Convert to data frame
movies <- data.frame(name, year, genre, length, user_rating, director, synopsis)
# Display the data frame using kable
kable(movies)
| name | year | genre | length | user_rating | director | synopsis |
|---|---|---|---|---|---|---|
| Alien | (1979) | Horror, Sci-Fi | 117 min | 8.5 | Ridley Scott | The crew of a commercial spacecraft encounters a deadly lifeform after investigating an unknown transmission. |
| Psycho | (1960) | Horror, Mystery, Thriller | 109 min | 8.5 | Alfred Hitchcock | A Phoenix secretary embezzles $40,000 from her employer’s client, goes on the run and checks into a remote motel run by a young man under the domination of his mother. |
| The Shining | (1980) | Drama, Horror | 146 min | 8.4 | Stanley Kubrick | A family heads to an isolated hotel for the winter where a sinister presence influences the father into violence, while his psychic son sees horrific forebodings from both past and future. |
| The Thing | (1982) | Horror, Mystery, Sci-Fi | 109 min | 8.2 | John Carpenter | A research team in Antarctica is hunted by a shape-shifting alien that assumes the appearance of its victims. |
| Tumbbad | (2018) | Drama, Fantasy, Horror | 104 min | 8.2 | Rahi Anil Barve | A mythological story about a goddess who created the entire universe. The plot revolves around the consequences when humans build a temple for her first-born. |
| The Exorcist | (1973) | Horror | 122 min | 8.1 | William Friedkin | When a young girl is possessed by a mysterious entity, her mother seeks the help of two Catholic priests to save her life. |
| Diabolique | (1955) | Crime, Drama, Horror | 117 min | 8.1 | Henri-Georges Clouzot | The wife and mistress of a loathed school principal plan to murder him with what they believe is the perfect alibi. |
| Rosemary’s Baby | (1968) | Drama, Horror | 137 min | 8.0 | Roman Polanski | A young couple trying for a baby moves into an aging, ornate apartment building on Central Park West, where they find themselves surrounded by peculiar neighbors. |
| What Ever Happened to Baby Jane? | (1962) | Drama, Horror, Thriller | 134 min | 8.0 | Robert Aldrich | A former child star torments her paraplegic sister in their decaying Hollywood mansion. |
| The Cabinet of Dr. Caligari | (1920) | Horror, Mystery, Thriller | 67 min | 8.0 | Robert Wiene | Hypnotist Dr. Caligari uses a somnambulist, Cesare, to commit murders. |
| Shaun of the Dead | (2004) | Comedy, Horror | 99 min | 7.9 | Edgar Wright | The uneventful, aimless lives of a London electronics salesman and his layabout roommate are disrupted by the zombie apocalypse. |
| Nosferatu | (1922) | Fantasy, Horror | 94 min | 7.9 | F.W. Murnau | Vampire Count Orlok expresses interest in a new residence and real estate agent Hutter’s wife. |
| King Kong | (1933) | Adventure, Horror, Sci-Fi | 100 min | 7.9 | Merian C. Cooper | A film crew goes to a tropical island for a location shoot, where they capture a colossal ape who takes a shine to their blonde starlet, and bring him back to New York City. |
| Get Out | (I) (2017) | Horror, Mystery, Thriller | 104 min | 7.8 | Jordan Peele | A young African-American visits his White girlfriend’s parents for the weekend, where his simmering uneasiness about their reception of him eventually reaches a boiling point. |
| Predator | (1987) | Action, Adventure, Horror | 107 min | 7.8 | John McTiernan | A team of commandos on a mission in a Central American jungle find themselves hunted by an extraterrestrial warrior. |
| Night of the Living Dead | (1968) | Horror, Thriller | 96 min | 7.8 | George A. Romero | A ragtag group of survivors barricade themselves in an old farmhouse to remain safe from a horde of flesh-eating ghouls that are ravaging the Northeast portion of the United States. |
| Freaks | (1932) | Drama, Horror | 64 min | 7.8 | Tod Browning | A circus’ beautiful trapeze artist agrees to marry the leader of side-show performers, but his deformed friends discover she is only marrying him for his inheritance. |
| Frankenstein | (1931) | Drama, Horror, Sci-Fi | 70 min | 7.8 | James Whale | Dr Henry Frankenstein is obsessed with assembling a living being from parts of several exhumed corpses. |
| Dawn of the Dead | (1978) | Horror, Thriller | 127 min | 7.8 | George A. Romero | During an escalating zombie epidemic, two Philadelphia SWAT team members, a traffic reporter and his TV executive girlfriend seek refuge in a secluded shopping mall. |
| Let the Right One In | (2008) | Drama, Fantasy, Horror | 114 min | 7.8 | Tomas Alfredson | Oskar, an overlooked and bullied boy, finds love and revenge through Eli, a beautiful but peculiar girl. |
| The Bride of Frankenstein | (1935) | Drama, Horror, Sci-Fi | 75 min | 7.8 | James Whale | Mary Shelley reveals the main characters of her novel survived: Dr. Frankenstein, goaded by an even madder scientist, builds his monster a mate. |
| The Innocents | (1961) | Horror | 100 min | 7.8 | Jack Clayton | A young governess for two children becomes convinced that the house and grounds are haunted. |
| Halloween | (1978) | Horror, Thriller | 91 min | 7.7 | John Carpenter | Fifteen years after murdering his sister on Halloween night 1963, Michael Myers escapes from a mental hospital and returns to the small town of Haddonfield, Illinois to kill again. |
| Evil Dead II | (1987) | Comedy, Horror | 84 min | 7.7 | Sam Raimi | The lone survivor of an onslaught of flesh-possessing spirits holes up in a cabin with a group of strangers while the demons continue their attack. |
| Invasion of the Body Snatchers | (1956) | Drama, Horror, Sci-Fi | 80 min | 7.7 | Don Siegel | A small-town doctor learns that the population of his community is being replaced by emotionless alien duplicates. |
| Saw | (2004) | Horror, Mystery, Thriller | 103 min | 7.6 | James Wan | Two strangers awaken in a room with no recollection of how they got there, and soon discover they’re pawns in a deadly game perpetrated by a notorious serial killer. |
| American Psycho | (2000) | Crime, Drama, Horror | 102 min | 7.6 | Mary Harron | A wealthy New York City investment banking executive, Patrick Bateman, hides his alternate psychopathic ego from his co-workers and friends as he delves deeper into his violent, hedonistic fantasies. |
| The Others | (2001) | Horror, Mystery, Thriller | 104 min | 7.6 | Alejandro Amenábar | In 1945, immediately following the end of Second World War, a woman who lives with her two photosensitive children on her darkened old family estate in the Channel Islands becomes convinced that the home is haunted. |
| What We Do in the Shadows | (2014) | Comedy, Horror | 86 min | 7.6 | Jemaine Clement | Viago, Deacon, and Vladislav are vampires who are struggling with the mundane aspects of modern life, like paying rent, keeping up with the chore wheel, trying to get into nightclubs, and overcoming flatmate conflicts. |
| Train to Busan | (2016) | Action, Horror, Thriller | 118 min | 7.6 | Sang-ho Yeon | While a zombie virus breaks out in South Korea, passengers struggle to survive on the train from Seoul to Busan. |
| The Fly | (1986) | Drama, Horror, Sci-Fi | 96 min | 7.6 | David Cronenberg | A brilliant but eccentric scientist begins to transform into a giant man/fly hybrid after one of his experiments goes horribly wrong. |
| Zombieland | (2009) | Action, Comedy, Horror | 88 min | 7.6 | Ruben Fleischer | A shy student trying to reach his family in Ohio, a gun-toting bruiser in search of the last Twinkie and a pair of sisters striving to get to an amusement park join forces in a trek across a zombie-filled America. |
| The Birds | (1963) | Drama, Horror, Mystery | 119 min | 7.6 | Alfred Hitchcock | A wealthy San Francisco socialite pursues a potential boyfriend to a small Northern California town that slowly takes a turn for the bizarre when birds of all kinds suddenly begin to attack people. |
| The Skin I Live In | (2011) | Drama, Horror, Mystery | 120 min | 7.6 | Pedro Almodóvar | A brilliant plastic surgeon, haunted by past tragedies, creates a type of synthetic skin that withstands any kind of damage. His guinea pig: a mysterious and volatile woman who holds the key to his obsession. |
| The Invisible Man | (1933) | Horror, Sci-Fi | 71 min | 7.6 | James Whale | A scientist finds a way of becoming invisible, but in doing so, he becomes murderously insane. |
| Peeping Tom | (1960) | Drama, Horror, Thriller | 101 min | 7.6 | Michael Powell | A young man murders women, using a movie camera to film their dying expressions of terror. |
| Vampire Hunter D: Bloodlust | (2000) | Animation, Action, Drama | 103 min | 7.6 | Yoshiaki Kawajiri | A legendary dhampir competes with a motley family of bounty hunters to return a young woman, who has been seemingly abducted by a vampire, to her family. |
| Repulsion | (1965) | Drama, Horror, Thriller | 105 min | 7.6 | Roman Polanski | A sex-repulsed woman who disapproves of her sister’s boyfriend sinks into depression and has horrific visions of rape and violence. |
| Eyes Without a Face | (1960) | Drama, Horror | 90 min | 7.6 | Georges Franju | A surgeon causes an accident which leaves his daughter disfigured and goes to extreme lengths to give her a new face. |
| The Conjuring | (2013) | Horror, Mystery, Thriller | 112 min | 7.5 | James Wan | Paranormal investigators Ed and Lorraine Warren work to help a family terrorized by a dark presence in their farmhouse. |
| Interview with the Vampire: The Vampire Chronicles | (1994) | Drama, Fantasy, Horror | 123 min | 7.5 | Neil Jordan | A vampire tells his epic life story: love, betrayal, loneliness, and hunger. |
| An American Werewolf in London | (1981) | Comedy, Horror | 97 min | 7.5 | John Landis | Two American college students on a walking tour of Britain are attacked by a werewolf that none of the locals will admit exists. |
| A Quiet Place | (2018) | Drama, Horror, Sci-Fi | 90 min | 7.5 | John Krasinski | A family struggles for survival in a world where most humans have been killed by blind but noise-sensitive creatures. They are forced to communicate in sign language to keep the creatures at bay. |
| The Omen | (1976) | Horror, Mystery | 111 min | 7.5 | Richard Donner | Mysterious deaths surround an American ambassador. Could the child that he is raising actually be the Antichrist? The Devil’s own son? |
| 28 Days Later | (2002) | Drama, Horror, Sci-Fi | 113 min | 7.5 | Danny Boyle | Four weeks after a mysterious, incurable virus spreads throughout the UK, a handful of survivors try to find sanctuary. |
| The Crow | (1994) | Action, Crime, Drama | 102 min | 7.5 | Alex Proyas | A man brutally murdered comes back to life as an undead avenger of his and his fiancée’s murder. |
| The Wicker Man | (1973) | Horror, Mystery, Thriller | 88 min | 7.5 | Robin Hardy | A puritan Police Sergeant arrives in a Scottish island village in search of a missing girl, who the Pagan locals claim never existed. |
| Tucker and Dale vs Evil | (2010) | Comedy, Horror | 89 min | 7.5 | Eli Craig | Affable hillbillies Tucker and Dale are on vacation at their dilapidated mountain cabin when they are mistaken for murderers by a group of preppy college students. |
| Braindead | (1992) | Comedy, Fantasy, Horror | 104 min | 7.5 | Peter Jackson | A young man’s mother is bitten by a Sumatran rat-monkey. She gets sick and dies, at which time she comes back to life, killing and eating dogs, nurses, friends, and neighbors. |
| Grindhouse | (2007) | Action, Horror, Thriller | 191 min | 7.5 | Robert Rodriguez | Quentin Tarantino and Robert Rodriguez’s homage to exploitation double features in the ’60s and ’70s with two back-to-back cult films that include previews of coming attractions between them. |
# Filter the data frame to get the information for the movie "Alien"
alien_movie <- movies[movies$name == "Alien", ]
# Print the information for the movie "Alien"
cat("Movie Name: ", alien_movie$name, "\n")
## Movie Name: Alien
cat("Year: ", alien_movie$year, "\n")
## Year: (1979)
cat("Genre: ", alien_movie$genre, "\n")
## Genre: Horror, Sci-Fi
cat("Length: ", alien_movie$length, "\n")
## Length: 117 min
cat("User Rating: ", alien_movie$user_rating, "\n")
## User Rating: 8.5
cat("Director: ", alien_movie$director, "\n")
## Director: Ridley Scott
cat("Synopsis for 'Alien' movie:\n", alien_movie$synopsis, "\n")
## Synopsis for 'Alien' movie:
## The crew of a commercial spacecraft encounters a deadly lifeform after investigating an unknown transmission.
This code does the following:
Extracts movie names, cleans up genre and synopsis. Stores movie information in a list (movie_info_list). Specifies the movie you want to convert to a CSV file. Checks if the chosen movie exists in the list. If the movie is found, it creates a data frame for the chosen movie and saves it as a CSV file with a filename based on the movie name. Replace “Alien” with the movie name you want to convert to a CSV file. The information for that movie will be saved in a CSV file with a filename like “Alien_info.csv.”
# Extract movie names from the web scraping
name <- page %>% html_nodes(".lister-item-header a") %>% html_text()
# Replace '\n' characters in 'genre' and 'synopsis'
genre <- page %>% html_nodes(".genre") %>% html_text()
genre <- gsub("\n", " ", genre)
synopsis <- page %>% html_nodes(".ratings-bar+ .text-muted") %>% html_text()
synopsis <- gsub("\n", " ", synopsis)
# Initialize an empty list to store movie information
movie_info_list <- list()
# Loop through the extracted movie names and extract information
for (movie_name in name) {
movie_data <- movies[movies$name == movie_name, ]
# Store the movie information in the list
movie_info_list[[movie_name]] <- movie_data
}
# Specify the movie you want to convert to CSV (e.g., "Alien")
chosen_movie <- "Alien"
# Check if the chosen movie exists in the list
if (chosen_movie %in% names(movie_info_list)) {
# Create a data frame with the information for the chosen movie
chosen_movie_data <- movie_info_list[[chosen_movie]]
# Define the filename for the CSV
csv_filename <- paste0(chosen_movie, "_info.csv")
# Write the chosen movie's information to a CSV file
write.csv(chosen_movie_data, csv_filename, row.names = FALSE)
cat("The information for '", chosen_movie, "' has been saved to '", csv_filename, "'.\n")
} else {
cat("Movie not found in the list.")
}
## The information for ' Alien ' has been saved to ' Alien_info.csv '.
The code goes through multiple website pages, extracting movie data for each page.
The “get_cast” function finds cast members’ names by taking movie links, reading the HTML, and using CSS selectors.
Store all this in the “horror-movies” data frame.
A loop navigates through website pages, creating URLs, reading HTML, and extracting data.
Use “sapply” to get cast information for each movie link.
Once all data is collected, the “movies” data frame is filled, and the loop moves to the next page.
You can view the scraped data and save it as a CSV file.
This code helps you gather movie data from IMDb for analysis or other purposes.
# Extract movie names from the web scraping
name <- page %>% html_nodes(".lister-item-header a") %>% html_text()
# Replace '\n' characters in 'genre' and 'synopsis'
genre <- page %>% html_nodes(".genre") %>% html_text()
genre <- gsub("\n", " ", genre)
synopsis <- page %>% html_nodes(".ratings-bar+ .text-muted") %>% html_text()
synopsis <- gsub("\n", " ", synopsis)
# Initialize an empty list to store movie information
movie_info_list <- list()
# Loop through the extracted movie names and extract information
for (movie_name in name) {
movie_data <- movies[movies$name == movie_name, ]
# Store the movie information in the list
movie_info_list[[movie_name]] <- movie_data
}
# Create a data frame with information for all movies
all_movies_data <- do.call(rbind, movie_info_list)
# Define the filename for the CSV
csv_filename <- "all_horror_movies_info.csv"
# Write information for all movies to a CSV file
write.csv(all_movies_data, csv_filename, row.names = FALSE)
cat("The information for all horror movies has been saved to '", csv_filename, "'.\n")
## The information for all horror movies has been saved to ' all_horror_movies_info.csv '.