Introducción al web scraping con R

Con el boom del comercio electrónico, las empresas se han conectado. Los clientes también buscan productos en línea. A diferencia del mercado fuera de línea, un cliente puede comparar el precio de un producto disponible en diferentes lugares en tiempo real.

Por lo tanto, los precios competitivos son algo que se ha convertido en la parte más crucial de una estrategia comercial.

Para mantener los precios de sus productos competitivos y atractivos, debe controlar y realizar un seguimiento de los precios establecidos por sus competidores. Si sabe cuál es la estrategia de precios de sus competidores, puede alinear su estrategia de precios para obtener una ventaja sobre ellos.

Por lo tanto, el seguimiento de precios se ha convertido en una parte vital del proceso de gestión de un negocio de comercio electrónico.

Quizás se pregunte cómo obtener los datos para comparar precios.

Las 3 formas principales de obtener los datos que necesita para comparar precios

1. Feeds de comerciantes

Como ya sabrá, hay varios sitios de comparación de precios disponibles en Internet. Estos sitios entran en una especie de entendimiento con las empresas en el que obtienen los datos directamente de ellos y que utilizan para comparar precios.

Estas empresas implementan una API o utilizan FTP para proporcionar los datos. Generalmente, una comisión de referencia es lo que hace que un sitio de comparación de precios sea financieramente viable.

2. Feeds de productos de API de terceros

Por otro lado, existen servicios que ofrecen datos de comercio electrónico a través de una API. Cuando se utiliza un servicio de este tipo, el tercero paga el volumen de datos.

3. Web Scraping

El web scraping es una de las formas más sólidas y fiables de obtener datos web de Internet. Se utiliza cada vez más en inteligencia de precios porque es una forma eficaz de obtener datos de productos de sitios de comercio electrónico.

Es posible que no tenga acceso a la primera y segunda opción. Por lo tanto, el web scraping puede acudir a su rescate. Puede utilizar el web scraping para aprovechar el poder de los datos y llegar a precios competitivos para su empresa.

El web scraping se puede utilizar para obtener precios actuales para el escenario actual del mercado y el comercio electrónico en general. Usaremos web scraping para obtener los datos de un sitio de comercio electrónico. En este blog, aprenderá cómo raspar los nombres y precios de productos de Amazon en todas las categorías, bajo una marca en particular.

La extracción de datos de Amazon periódicamente puede ayudarlo a realizar un seguimiento de las tendencias de precios del mercado y permitirle establecer sus precios en consecuencia.

Tabla de contenido

  1. Web scraping para comparar precios
  2. Web scraping en R
  3. Implementación
  4. Nota final

1. Web scraping para comparar precios

Como dice la sabiduría del mercado, el precio lo es todo. Los clientes toman sus decisiones de compra en función del precio. Basan su comprensión de la calidad de un producto en el precio. En definitiva, el precio es lo que impulsa a los clientes y, por tanto, al mercado.

Por lo tanto, los sitios de comparación de precios tienen una gran demanda. Los clientes pueden navegar fácilmente por todo el mercado al observar los precios del mismo producto en todas las marcas. Estos sitios web de comparación de precios extraen el precio del mismo producto de diferentes sitios.

Junto con el precio, los sitios web de comparación de precios también recopilan datos como la descripción del producto, las especificaciones técnicas y las características. Proyectan toda la gama de información en una sola página de forma comparativa.

Esto responde a la pregunta que el posible comprador ha hecho en su búsqueda. Ahora, el posible comprador puede comparar los productos y sus precios, junto con información como las características, el pago y las opciones de envío, para que pueda identificar la mejor oferta posible disponible.

La optimización de precios tiene su impacto en el negocio en el sentido de que tales técnicas pueden mejorar los márgenes de beneficio en un 10%.

El comercio electrónico tiene que ver con precios competitivos y también se ha extendido a otros dominios comerciales. Tomemos el caso de los viajes. Ahora incluso los sitios web relacionados con viajes extraen el precio de los sitios web de las aerolíneas en tiempo real para proporcionar la comparación de precios de diferentes aerolíneas.

El único desafío en esto es actualizar los datos en tiempo real y mantenerse actualizado cada segundo a medida que los precios cambian en los sitios de origen. Los sitios de comparación de precios utilizan trabajos de Cron o en el momento de la vista para actualizar el precio. Sin embargo, dependerá de la configuración del propietario del sitio.

Aquí es donde este blog puede ayudarlo: podrá elaborar un script de extracción que puede personalizar para satisfacer sus necesidades. Podrá extraer feeds de productos, imágenes, precios y todos los demás detalles relevantes sobre un producto de varios sitios web diferentes. Con esto, puede crear su potente base de datos para el sitio de comparación de precios.

2. Web scraping en R

La comparación de precios se vuelve engorrosa porque obtener datos web no es tan fácil: existen tecnologías como HTML, XML y JSON para distribuir el contenido.

Entonces, para obtener los datos que necesita, debe navegar de manera efectiva a través de estas diferentes tecnologías. R puede ayudarlo a acceder a los datos almacenados en estas tecnologías. Sin embargo, requiere un conocimiento profundo de R antes de comenzar.

¿Qué es R?

El web scraping es una tarea avanzada que no mucha gente realiza. El web scraping con R es, sin duda, una programación técnica y avanzada. Una comprensión adecuada de R es esencial para el web scraping de esta manera.

Para empezar, R es un lenguaje para computación estadística y gráficos. Los estadísticos y los mineros de datos usan mucho R debido a su software estadístico en evolución y su enfoque en el análisis de datos.

Una de las razones por las que R es uno de los favoritos entre este grupo de personas es la calidad de los gráficos que pueden elaborarse, incluidos los símbolos y fórmulas matemáticos cuando sea necesario.

R es maravilloso porque ofrece una amplia variedad de funciones y paquetes que pueden manejar tareas de minería de datos.

rvest, RCrawler, etc.son paquetes de R que se utilizan para los procesos de recopilación de datos.

In this segment, we will see what kinds of tools are required to work with R to carry out web scraping. We will see it through the use case of Amazon website from where we will try to get the product data and store it in JSON form.

Requirements

In this use case, knowledge of R is essential and I am assuming that you have a basic understanding of R. You should be aware of at least any one R interface, such as RStudio. The base R installation interface is fine.

If you are not aware of R and the other associated interfaces, you should go through this tutorial.

Now let’s understand how the packages we’re going to use will be installed.

Packages:

1. rvest

Hadley Wickham authored the rvest package for web scraping in R. rvest is useful in extracting the information you need from web pages.

Along with this, you also need to install the selectr and ‘xml2’ packages.

Installation steps:

install.packages(‘selectr’)
install.packages(‘xml2’)
install.packages(‘rvest’)

rvest contains the basic web scraping functions, which are quite effective. Using the following functions, we will try to extract the data from web sites.

  • read_html(url) : scrape HTML content from a given URL
  • html_nodes(): identifies HTML wrappers.
  • html_nodes(“.class”): calls node based on CSS class
  • html_nodes(“#id”): calls node based on id
  • html_nodes(xpath=”xpath”): calls node based on xpath (we’ll cover this later)
  • html_attrs(): identifies attributes (useful for debugging)
  • html_table(): turns HTML tables into data frames
  • html_text(): strips the HTML tags and extracts only the text

2. stringr

stringr comes into play when you think of tasks related to data cleaning and preparation.

There are four essential sets of functions in stringr:

  • stringr functions are useful because they enable you to work around the individual characters within the strings in character vectors
  • there are whitespace tools which can be used to add, remove, and manipulate whitespace
  • there are locale sensitive operations whose operations will differ from locale to locale
  • there are pattern matching functions. These functions recognize four parts of pattern description. Regular expressions are the standard one but there are other tools as well

Installation

install.packages(‘stringr’)

3. jsonlite

What makes the jsonline package useful is that it is a JSON parser/generator which is optimized for the web.

It is vital because it enables an effective mapping between JSON data and the crucial R data types. Using this, we are able to convert between R objects and JSON without loss of type or information, and without the need for any manual data wrangling.

This works really well for interacting with web APIs, or if you want to create ways through which data can travel in and out of R using JSON.

Installation

install.packages(‘jsonlite’)

Before we jump-start into it, let’s see how it works:

It should be clear at the outset that each website is different, because the coding that goes into a website is different.

Web scraping is the technique of identifying and using these patterns of coding to extract the data you need. Your browser makes the website available to you from HTML. Web scraping is simply about parsing the HTML made available to you from your browser.

Web scraping has a set process that works like this, generally:

  • Access a page from R
  • Instruct R where to “look” on the page
  • Convert data in a usable format within R using the rvest package

Now let’s go to implementation to understand it better.

3. Implementation

Let’s implement it and see how it works. We will scrape the Amazon website for the price comparison of a product called “One Plus 6”, a mobile phone.

You can see it here.

Step 1: Loading the packages we need

We need to be in the console, at R command prompt to start the process. Once we are there, we need to load the packages required as shown below:

#loading the package:> library(xml2)> library(rvest)> library(stringr)

Step 2: Reading the HTML content from Amazon

#Specifying the url for desired website to be scrappedurl <- ‘//www.amazon.in/OnePlus-Mirror-Black-64GB-Memory/dp/B0756Z43QS?tag=googinhydr18418-21&tag=googinkenshoo-21&ascsubtag=aee9a916-6acd-4409-92ca-3bdbeb549f80’
#Reading the html content from Amazonwebpage <- read_html(url)

In this code, we read the HTML content from the given URL, and assign that HTML into the webpage variable.

Step 3: Scrape product details from Amazon

Now, as the next step, we will extract the following information from the website:

Title: The title of the product.

Price: The price of the product.

Description: The description of the product.

Rating: The user rating of the product.

Size: The size of the product.

Color: The color of the product.

This screenshot shows how these fields are arranged.

Next, we will make use of HTML tags, like the title of the product and price, for extracting data using Inspect Element.

In order to find out the class of the HTML tag, use the following steps:

=> go to chrome browser => go to this URL => right click => inspect element

NOTE: If you are not using the Chrome browser, check out this article.

Based on CSS selectors such as class and id, we will scrape the data from the HTML. To find the CSS class for the product title, we need to right-click on title and select “Inspect” or “Inspect Element”.

As you can see below, I extracted the title of the product with the help of html_nodes in which I passed the id of the title — h1#title — and webpage which had stored HTML content.

I could also get the title text using html_text and print the text of the title with the help of the head () function.

#scrape title of the product> title_html  title  head(title)

The output is shown below:

We could get the title of the product using spaces and \n.

The next step would be to remove spaces and new line with the help of the str_replace_all() function in the stringr library.

# remove all space and new linesstr_replace_all(title, “[\r\n]” , “”)

Output:

Now we will need to extract the other related information of the product following the same process.

Price of the product:

# scrape the price of the product> price_html  price <- html_text(price_html)
# remove spaces and new line> str_replace_all(title, “[\r\n]” , “”)
# print price value> head(price)

Output:

Product description:

# scrape product description> desc_html  desc <- html_text(desc_html)
# replace new lines and spaces> desc  desc  head(desc)

Output:

Rating of the product:

# scrape product rating > rate_html  rate <- html_text(rate_html)
# remove spaces and newlines and tabs > rate  rate <- str_trim(rate)
# print rating of the product> head(rate)

Output:

Size of the product:

# Scrape size of the product> size_html  size_html  size <- html_text(size_html)
# remove tab from text> size <- str_trim(size)
# Print product size> head(size)

Output:

Color of the product:

# Scrape product color> color_html  color_html  color <- html_text(color_html)
# remove tabs from text> color <- str_trim(color)
# print product color> head(color)

Output:

Step 4: We have successfully extracted data from all the fields which can be used to compare the product information from another site.

Let’s compile and combine them to work out a dataframe and inspect its structure.

#Combining all the lists to form a data frameproduct_data <- data.frame(Title = title, Price = price,Description = desc, Rating = rate, Size = size, Color = color)
#Structure of the data framestr(product_data)

Output:

In this output we can see all the scraped data in the data frames.

Step 5: Store data in JSON format:

As the data is collected, we can carry out different tasks on it such as compare, analyze, and arrive at business insights about it. Based on this data, we can think of training machine learning models over this.

Data would be stored in JSON format for further process.

Follow the given code and get the JSON result.

# Include ‘jsonlite’ library to convert in JSON form.> library(jsonlite)
# convert dataframe into JSON format> json_data <- toJSON(product_data)
# print output> cat(json_data)

In the code above, I have included jsonlite library for using the toJSON() function to convert the dataframe object into JSON form.

At the end of the process, we have stored data in JSON format and printed it.

It is possible to store data in a csv file also or in the database for further processing, if we wish.

Output:

Following this practical example, you can also extract the relevant data for the same from product from //www.oneplus.in/6 and compare with Amazon to work out the fair value of the product. In the same way, you can use the data to compare it with other websites.

4. End note

As you can see, R can give you great leverage in scraping data from different websites. With this practical illustration of how R can be used, you can now explore it on your own and extract product data from Amazon or any other e-commerce website.

A word of caution for you: certain websites have anti-scraping policies. If you overdo it, you will be blocked and you will begin to see captchas instead of product details. Of course, you can also learn to work your way around the captchas using different services available. However, you do need to understand the legality of scraping data and whatever you are doing with the scraped data.

Feel free to send to me your feedback and suggestions regarding this post!