Bevezetés a webes kaparáshoz az R használatával

Az e-kereskedelem fellendülésével a vállalkozások online kapcsolatba léptek. Az ügyfelek is online keresik a termékeket. Az offline piactértől eltérően az ügyfél valós időben összehasonlíthatja a különböző helyeken elérhető termék árát.

Ezért a versenyképes árképzés az üzleti stratégia legfontosabb részévé vált.

Ahhoz, hogy termékei árai versenyképesek és vonzóak maradjanak, figyelemmel kell kísérnie és nyomon kell követnie a versenytársak által meghatározott árakat. Ha tudja, mi a versenytársai árstratégiája, ennek megfelelően összehangolhatja az árstratégiáját, hogy előnyt szerezzen felettük.

Ennélfogva az árfigyelés az e-kereskedelmi vállalkozás működtetésének létfontosságú részévé vált.

Elgondolkodhat azon, hogyan lehet megszerezni az adatokat az árak összehasonlításához.

Az ár-összehasonlításhoz szükséges adatok megszerzésének három legfontosabb módja

1. Kereskedők hírcsatornái

Mint tudhatja, az interneten számos ár-összehasonlító oldal érhető el. Ezek a webhelyek egyfajta megértésbe kerülnek a vállalkozásokkal, ahol közvetlenül tőlük kapják az adatokat, és amelyeket az árak összehasonlítására használnak fel.

Ezek a vállalkozások API-t hoznak létre, vagy FTP-t használnak az adatok megadásához. Általában az ajánlási jutalék teszi az ár-összehasonlító webhelyet pénzügyileg életképessé.

2. Harmadik féltől származó API-k termékcsatornái

Másrészt vannak olyan szolgáltatások, amelyek API-n keresztül kínálnak e-kereskedelmi adatokat. Ilyen szolgáltatás használatakor a harmadik fél fizet az adatok mennyiségéért.

3. Webes kaparás

A webes adatgyűjtés az egyik legerőteljesebb és legmegbízhatóbb módszer az internetes adatok lekérésére az internetről. Egyre inkább használják az árinformációkban, mert ez hatékony módja a termékadatok megszerzésének az e-kereskedelmi webhelyekről.

Lehet, hogy nincs hozzáférése az első és a második lehetőséghez. Ennélfogva a webes kaparás megmenthet. A webes kaparás segítségével kiaknázhatja az adatok erejét, hogy versenyképes árakat érhessen el vállalkozásának.

A webes kaparás felhasználható az aktuális piaci forgatókönyv aktuális árának és általában az e-kereskedelemnek az megszerzésére. Webes kaparással fogjuk felhasználni az adatokat egy e-kereskedelmi webhelyről. Ebben a blogban megtudhatja, hogyan lehet minden kategóriában, egy adott márkanév alatt az Amazon termékeinek nevét és árát kaparni.

Az Amazon rendszeres adatkivétele segíthet nyomon követni az árképzés piaci trendjeit, és lehetővé teszi az árak ennek megfelelő beállítását.

Tartalomjegyzék

  1. Webes kaparás az árak összehasonlításához
  2. Webes kaparás R-ben
  3. Végrehajtás
  4. Végjegyzet

1. Webes kaparás az árak összehasonlításához

Ahogy a piaci bölcsesség mondja, az ár minden. Az ügyfelek az ár alapján hozzák meg vásárlási döntéseiket. A termék minőségének megértését az árra alapozzák. Röviden: az ár vezérli az ügyfeleket és így a piacot.

Ezért az ár-összehasonlító oldalakra nagy a kereslet. Az ügyfelek könnyen eligazodhatnak az egész piacon, ha megnézik ugyanazon termék árait a márkák között. Ezek az ár-összehasonlító webhelyek ugyanazon termék árát vonják le különböző webhelyekről.

Az ár mellett az ár-összehasonlító webhelyek olyan adatokat is lekaparnak, mint a termék leírása, a műszaki specifikációk és a szolgáltatások. Összehasonlító módon egyetlen oldalon vetítik az információk teljes skáláját.

Ez megválaszolja azt a kérdést, amelyet a leendő vevő feltett keresése során. Most a leendő vevő összehasonlíthatja a termékeket és azok árait, valamint az olyan információkat, mint a szolgáltatások, a fizetési és a szállítási lehetőségek, hogy azonosítsák a lehető legjobb ajánlatot.

Az ároptimalizálás abból a szempontból érinti az üzletet, hogy az ilyen technikák 10% -kal növelhetik a haszonkulcsot.

Az e-kereskedelem a versenyképes árakról szól, és elterjedt más üzleti területeken is. Vegyük az utazás esetét. Most még az utazással kapcsolatos webhelyek is lekaparják az árat a légitársaságok webhelyeiről valós időben , hogy a különböző légitársaságok árát összehasonlítsák.

Az egyetlen kihívás ebben az, hogy valós időben frissítse az adatokat, és másodpercenként naprakész legyen, mivel az árak folyamatosan változnak a forrás webhelyeken. Az ár-összehasonlító webhelyek Cron-feladatokat vagy a megtekintési időben használják az ár frissítéséhez. Ez azonban a webhely tulajdonosának konfigurációján nyugszik.

Ez az a hely, ahol ez a blog segíthet - képes lesz kidolgozni egy kaparó szkriptet, amelyet személyre szabhat az Ön igényeinek megfelelően. Számos különböző webhelyről kinyerheti a termék hírcsatornáit, képeit, árát és minden egyéb releváns részletet a termékkel kapcsolatban. Ezzel létrehozhatja a hatékony adatbázist az ár-összehasonlító webhelyhez.

2. Webes kaparás R-ben

Az ár-összehasonlítás nehézkessé válik, mert a webes adatok megszerzése nem olyan egyszerű - vannak olyan technológiák, mint a HTML, az XML és a JSON a tartalom terjesztésére.

Tehát a szükséges adatok megszerzéséhez hatékonyan kell navigálnia ezen különböző technológiák között. Az R segíthet az ezekben a technológiákban tárolt adatok elérésében. Ehhez azonban kissé alaposan meg kell ismernie az R-t, mielőtt elkezdené.

Mi az R?

Web scraping is an advanced task that not many people perform. Web scraping with R is, certainly, technical and advanced programming. An adequate understanding of R is essential for web scraping in this way.

To start with, R is a language for statistical computing and graphics. Statisticians and data miners use R a lot due to its evolving statistical software, and its focus on data analysis.

One reason R is such a favorite among this set of people is the quality of plots which can be worked out, including mathematical symbols and formulae wherever required.

R is wonderful because it offers a vast variety of functions and packages that can handle data mining tasks.

rvest, RCrawler etc are R packages used for data collection processes.

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!