Website Crawling and SEO extraction with Rcrawler
This section is relying on a package called Rcrawler by Salim Khalil. It’s a very handy crawler with some nice functionalities.

Installation

After R is being installed and rstudio launched, same as always, we’ll install and load our package:
1
#install to be run once
2
install.packages("Rcrawler")
3
# and loading
4
library(Rcrawler)
Copied!

Crawl an entire website with Rcrawler

To launch a simple website analysis, you only need this line of code:
1
Rcrawler(Website = "https://www.gokam.co.uk/")
Copied!
It will crawl the entire website and provide you with the data
Less than 30s to crawl a small website
After the crawl is being done, you’ll have access to:
The INDEX variable
it’s a data frame, if don’t know what’s a data frame, it’s like an excel file. Please note that it will be overwritten every time so export it if you want to keep it!
To take a look at it, just run
1
View(INDEX)
Copied!
INDEX data frame
Most of the columns are self-explanatory. Usually, the most interesting ones are ‘Http Resp‘ and ‘Level
The Level is what SEOs call “crawl depth” or “page depth”. With it, you can easily check how far from the homepage some webpages are.
Quick example with BrightonSEO website, let’s do a quick ‘ggplot’ and we’ll be able to see pages
page count by level
1
#here the code to run to see the plot
2
3
# install ggplot plot library to be run once
4
install.packages("ggplot2")
5
# Loading library
6
library(ggplot2)
7
# Convert Level to number
8
INDEX$Level <- as.integer(INDEX$Level)
9
10
# Make plot
11
# 1 define dimensions (only 'Level')
12
# 2 set up the plot type
13
# 3 customise the x scale, easier to read
14
ggplot(INDEX, aes(x=Level))+
15
geom_bar()+
16
scale_x_continuous(breaks=c(1:10))
17
18
19
#alternative command to count webpages per Level
20
table(INDEX$Level)
21
22
# Should display something like that:
23
# 0 1 2 3 4 5 6 7 8 9 10
24
# 1 32 306 91 116 127 61 54 90 149 255
Copied!
HTML Files
By default, the rcrawler function also store HTML files in your ‘working directory’. Update location by running setwd() function
Let’s go deeper into options by replying to the most commons questions:

So how to extract metadata while crawling?

It’s possible to extract any elements from webpages, using a CSS or XPath selector. We’ll have to use 2 new parameters
  • PatternsNames to name the new parameters
  • ExtractXpathPat or ExtractCSSPat to setup where to grab it in the web page
Let’s take an example:
1
#what we want to extract
2
CustomLabels <- c("title",
3
"h1",
4
"canonical tag",
5
"meta robots",
6
"hreflang",
7
"body class")
8
9
# How to grab it
10
CustomXPaths <- c("///title",
11
"///h1",
12
"//link[@rel='canonical']/@href",
13
"//meta[@rel='robots']/@content",
14
"//link[@rel='alternate']/@hreflang",
15
"//body/@class")
16
17
Rcrawler(Website = "https://www.brightonseo.com/",
18
ExtractXpathPat = CustomXPaths, PatternsNames = CustomLabels)
Copied!
You can access the scraped data in two ways:
  • option 1 = DATA – it’s an environment variable that you can directly access using the console. A small warning, it’s a ‘list’ a little less easy to read
View(DATA) will display something like that
If you want to convert it to a data frame, easier to deal with, here the code:
1
NEWDATA <- data.frame(matrix(unlist(DATA), nrow=length(DATA), byrow=T))
Copied!
  • option 2 = extracted_data.csv It’s a CSV file that has been saved inside your working directory along with the HTML files.
It might be useful to merge INDEX and NEWDATA files, here the code
1
MERGED <- cbind(INDEX,NEWDATA)
Copied!
As an example, let’s try to collect webpage type using scraped body class
Seems that the first word is the page type
Let’s extract the first word and feed it inside a new column
1
MERGED$pagetype <- str_split_fixed(MERGED$X7, " ", 2)[,1]
Copied!
A little bit a cleaning to make the labels easier to read
1
MERGED$pagetype_short <- str_replace(MERGED$pagetype, "-default", "")
2
MERGED$pagetype_short <- str_replace(MERGED$pagetype_short, "-template", "")
3
4
#it's basically deleting "-default" and "-template" from strings
5
#as it doesn't help that much understanding data
Copied!
the 3 steps being displayed
And then a quick ggplot
1
#loading graphic library
2
library(ggplot2)
3
4
5
p <- ggplot(MERGED, aes(x=Level, fill=pagetype_short))+
6
geom_histogram(stat="count")+
7
scale_x_continuous(breaks=c(1:10))
8
9
p
10
Copied!
Count of Pagetype per level
Want to see something even cooler?

An interactive graph

1
#install package plotly the first time
2
#install.packages("plotly")
3
library(plotly)
4
ggplotly(p, tooltip = c("count","pagetype_short"))
Copied!
An interactive graph
This is a static HTML file that can be store anywhere, even on my shared hosting

Explore Crawled Data with rpivottable

1
#install package rpivottable the first time
2
#install.packages("rpivottable")
3
# And loading
4
library(rpivottable)
5
# launch
6
toolrpivotTable(MERGED)
Copied!
This create a drag & drop pivot explorer
It’s also possible make some quick data viz

Extract more data without having to recrawl

All the HTML files are stored in your hard drive, so if you need more data extracted, it’s entirely possible.
You can list your recent crawl by using ListProjects() function,
it displays 2 recent crawling projects
First, we’re going to load the crawling project HTML files:
1
LastHTMLDATA <- LoadHTMLFiles("gokam.co.uk-242115", type = "vector")
2
# or to simply grab the last one:
3
LastHTMLDATA <- LoadHTMLFiles(ListProjects()[1], type = "vector")
Copied!
1
LastHTMLDATA <- as.data.frame(LastHTMLDATA)
2
colnames(LastHTMLDATA) <- 'html'
3
LastHTMLDATA$html <- as.character(LastHTMLDATA$html)
Copied!
Let’s say you forgot to grab h2’s and h3’s you can extract them again using the ContentScraper() also included inside rcrawler package.
1
for(i in 1:nrow(LastHTMLDATA)) {
2
LastHTMLDATA$title[i] <- ContentScraper(HTmlText = LastHTMLDATA$html[i] ,XpathPatterns = "//title")
3
LastHTMLDATA$h1[i] <- ContentScraper(HTmlText = LastHTMLDATA$html[i] ,XpathPatterns = "//h1")
4
LastHTMLDATA$h2[i] <- ContentScraper(HTmlText = LastHTMLDATA$html[i] ,XpathPatterns = "//h2")
5
LastHTMLDATA$h3[i] <- ContentScraper(HTmlText = LastHTMLDATA$html[i] ,XpathPatterns = "//h3")
6
}
Copied!

Categorize URLs using Regex

For those not afraid of regex, here is a complimentary script to categorize URLs. Be careful the regex order is important, some values can overwrite others. Usually, it’s a good idea to place the home page last
1
# define a default category
2
3
INDEX$UrlCat <- "Not match"
4
5
6
7
# create category name
8
9
category_name <- c("Category", "Dates", "author page", "Home page")
10
11
12
# create category regex, must be the same length
13
14
category_regex <- c("category", "2019", "author","example\.com.\/quot;)
15
16
17
18
# categorize
19
20
for(i in 1:length(category_name)){
21
22
# display a dot to show the progress
23
cat(".")
24
# run regex test and update value if it matches
25
# otherwise leave the previous value
26
INDEX$UrlCat <- ifelse(grepl(category_regex[i], INDEX$Url, ignore.case = T), category_name[i], INDEX$UrlCat)
27
28
}
29
30
31
# View variable to debug
32
33
View(INDEX)
Copied!

What if I want to follow robots.txt rules?

just had Obeyrobots parameter
1
#like that
2
Rcrawler(Website = "https://www.gokam.co.uk/", Obeyrobots = TRUE)
Copied!

What if I want to limit crawling speed?

By default, this crawler is rather quick and can grab a lot of webpage in no times. To every advantage an inconvenience, it’s fairly easy to wrongly detected as a DOS. To limit the risks, I suggest you use the parameter RequestsDelay. it’s the time interval between each round of parallel HTTP requests, in seconds. Example
1
# this will add a 10 secondes delay between
2
Rcrawler(Website = "https://www.example.com/", RequestsDelay=10)
Copied!
Other interesting limitation options:
no_cores: specify the number of clusters (logical cpu) for parallel crawling, by default it’s the numbers of available cores.
no_conn: it’s the number of concurrent connections per one core, by default it takes the same value of no_cores.

What if I want to crawl only a subfolder?

2 parameters help you do that. crawlUrlfilter will limit the crawl, dataUrlfilter will tell from which URLs data should be extracted
1
Rcrawler(Website = "http://www.glofile.com/sport/", dataUrlfilter ="/sport/", crawlUrlfilter="/sport/" )
Copied!

How to change user-agent?

1
#as simply as that
2
Rcrawler(Website = "http://www.example.com/", Useragent="Mozilla 3.11")
Copied!

What if my IP is banned?

option 1: Use a VPN on your computer
Option 2: use a proxy
Use the httr package to set up a proxy and use it
1
# create proxy configuration
2
proxy <- httr::use_proxy("190.90.100.205",41000)
3
# use proxy configuration
4
Rcrawler(Website = "https://www.gokam.co.uk/", use_proxy = proxy)
Copied!
Where to find proxy? It’s been a while I didn’t need one so I don’t know.
By default, RCrawler doesn’t save internal links, you have to ask for them explicitly by using NetworkData option, like that:
1
Rcrawler(Website = "https://www.gokam.co.uk/", NetworkData = TRUE)
Copied!
Then you’ll have two new variables available at the end of the crawling:
  • NetwIndex var that is simply all the webpage URLs. The row number are the same than locally stored HTML files, so row n°1 = homepage = 1.html
NetwIndex data frame
  • NetwEdges with all the links. It’s a bit confusing so let me explain:
NetwEdges data frame
Each row is a link. From and To columns indicate “from” which page “to” which page are each link. On the image above: row n°1 is a link from homepage (page n°1) to homepage row n°2 is a link from homepage to webpage n°2. According to NetwIndex variable, page n°2 is the article about rvest. etc…
Weight is the Depth level where the link connection has been discovered. All the first rows are from the homepage so Level 0. Type is either 1 for internal hyperlinks or 2 for external hyperlinks
I guess you guys are interested in counting links. Here is the code to do it. I won’t go into too many explanations, it would be too long. if you are interested (and motivated) go and check out the dplyr package and specifically Data Wrangling functions
Count outbound links
1
count_from <- NetwEdges[,1:2] %>%
2
#grabing the first two columns
3
distinct() %>%
4
# if there are several links from and to the same page, the duplicat will be removed.
5
group_by(From) %>%
6
summarise(n = n())
7
# the counting
8
View(count_from)
9
# we want to view the results
Copied!
the homepage (n°1) has 13 outbound links
To make it more readable let’s replace page IDs with URLs
1
count_from$To <- NetwIndex
2
View(count_from)
Copied!
using website URLs
Count inbound links
The same thing but the other way around
1
count_to -> NetwEdges[,1:2] %>%
2
#grabing the first two columns
3
distinct() %>%
4
# if there are several links from and to the same page, the duplicat will be removed.
5
group_by(To) %>%
6
summarise(n = n())
7
# the counting
8
View(count_to)
9
10
# we want to view the results
Copied!
count of inbound links
Again to make it more readable
1
count_to$To <- NetwIndexView(count_to)
Copied!
using website URLs
So the useless ‘author page‘ has 14 links pointing at it, as many as the homepage… Maybe I should fix this one day.

Compute ‘Internal Page Rank’

What if a website is using a JavaScript framework like React or Angular?

RCrawler handly includes Phantom JS, the classic headless browser. Here is how to to use
1
# Download and install phantomjs headless browser
2
# takes 20-30 seconds usually
3
install_browser()
4
5
# start browser process
6
br <-run_browser()
Copied!
After that, reference it as an option
1
Rcrawler(Website = "https://www.example.com/", Browser = br)
2
3
# don't forget to stop browser afterwards
4
stop_browser(br)
Copied!
It’s fairly possible to run 2 crawls, one with and one without, and compare the data afterwards
This Browser option can also be used with the other Rcrawler functions.
⚠️ Rendering webpage means every Javascript files will be run, including Web Analytics tags. If you don’t take the necessary precaution, it’ll change your Web Analytics data

So what’s the catch?

Rcrawler is a great tool but it’s far from being perfect. SEO will definitely miss a couple of things like there is no internal dead links report, It doesn’t grab nofollow attributes on Links and there is always a couple of bugs here and there, but overall it’s a great tool to have. Another concern is the git repo which is quite inactive. This is it. I hope you did find this article useful, reach to me for slow support, bugs/corrections or ideas for new articles. Take care.
ref: Khalil, S., & Fakir, M. (2017). RCrawler: An R package for parallel web crawling and scraping. SoftwareX, 6, 98-106.