Sissejuhatus veebi kraapimisele R abil

E-kaubanduse buumiga on ettevõtted võrku läinud. Ka kliendid otsivad tooteid veebist. Erinevalt võrguühenduseta turust saab klient võrrelda erinevates kohtades saadaval oleva toote hinda reaalajas.

Seetõttu on konkurentsivõimeline hinnakujundus midagi, millest on saanud äristrateegia kõige olulisem osa.

Toodete hindade konkurentsivõime ja atraktiivsuse säilitamiseks peate jälgima ja jälgima konkurentide kehtestatud hindu. Kui teate, milline on teie konkurentide hinnastrateegia, saate vastavalt oma hinnastrateegia joondada, et neist eeliseid saada.

Seega on hinnaseirest saanud e-kaubanduse äri juhtimise oluline osa.

Võite mõelda, kuidas saada andmeid kätte hindade võrdlemiseks.

3 parimat viisi hindade võrdlemiseks vajalike andmete saamiseks

1. Kaupmeeste kanalid

Nagu teate, on Internetis saadaval mitu hinnavõrdlussaiti. Need saidid saavad ettevõtetega omamoodi arusaama, kus nad saavad andmed otse neilt ja mida nad kasutavad hindade võrdlemiseks.

Need ettevõtted asutasid API või kasutavad andmete edastamiseks FTP-d. Üldiselt on saatekomisjon see, mis muudab hinnavõrdlussaidi rahaliselt tasuvaks.

2. Kolmanda osapoole API-de tootevood

Teiselt poolt on teenuseid, mis pakuvad e-kaubanduse andmeid API kaudu. Sellise teenuse kasutamisel maksab andmete maht kolmanda osapoole eest.

3. Veebikraapimine

Veebi kraapimine on üks kõige kindlam ja usaldusväärsem viis veebiandmete hankimiseks Internetist. Seda kasutatakse üha enam hinnaküsimustes, kuna see on tõhus viis tooteandmete hankimiseks e-kaubanduse saitidelt.

Teil ei pruugi olla juurdepääsu esimesele ja teisele valikule. Seega võib veebi kraapimine teile appi tulla. Veebikraapimist saate kasutada andmete võimsuse ärakasutamiseks, et jõuda oma ettevõtte konkurentsivõimelise hinnaga.

Veebikraapimist saab kasutada praeguse turustsenaariumi ja e-kaubanduse jaoks praeguste hindade saamiseks. E-kaubanduse saidilt andmete saamiseks kasutame veebi kraapimist. Selles ajaveebis saate teada, kuidas kraapida Amazoni toodete nimesid ja hindu kõigis kategooriates, kindla kaubamärgi all.

Amazonist perioodiliselt andmete väljavõtmine aitab teil jälgida hinnakujunduse turusuundumusi ja võimaldada teil vastavalt oma hindu määrata.

Sisukord

  1. Veebikraapimine hindade võrdlemiseks
  2. Veebis kraapimine R-s
  3. Rakendamine
  4. Lõpunoot

1. Veebikraapimine hindade võrdlemiseks

Nagu turutarkus ütleb, on hind kõik. Kliendid teevad ostuotsused hinna põhjal. Nad tuginevad toote kvaliteedi mõistmisel hinnale. Lühidalt, hind on see, mis juhib kliente ja seega ka turgu.

Seetõttu on hinnavõrdlussaitidel suur nõudlus. Kliendid saavad hõlpsasti navigeerida kogu turul, vaadates sama toote hindu kaubamärkide lõikes. Need hinnavõrdlusveebisaidid pakuvad sama toote hinda erinevatelt saitidelt.

Lisaks hinnale kraapivad hinnavõrdluse veebisaidid ka selliseid andmeid nagu toote kirjeldus, tehnilised näitajad ja funktsioonid. Nad projitseerivad kogu infovaru võrdlevalt ühel lehel.

See vastab küsimusele, mida potentsiaalne ostja on oma otsinguil esitanud. Nüüd saab tulevane ostja võrrelda tooteid ja nende hindu koos teabega, näiteks funktsioonide, maksmise ja saatmisvõimalustega, et leida võimalikult hea tehing.

Hinnakujunduse optimeerimine mõjutab äritegevust selles mõttes, et sellised meetodid võivad suurendada kasumimarginaali 10%.

E-kaubandus on seotud konkurentsivõimelise hinnakujundusega ja see on levinud ka teistesse ärivaldkondadesse. Võtame reisimise juhtumi. Nüüd kraabivad isegi reisimisega seotud veebisaidid reaalajas lennufirmade veebisaitidelt hinna, et pakkuda erinevate lennufirmade hinnavõrdlust.

Ainus väljakutse on andmete värskendamine reaalajas ja iga sekundi ajakohasus, kuna hinnad lähte saitidel pidevalt muutuvad. Hinnavõrdlussaidid kasutavad hinna värskendamiseks Croni töid või vaatamise ajal. Kuid see sõltub saidi omaniku konfiguratsioonist.

Siit saab see ajaveeb teid aidata - saate välja töötada kraapimisskripti, mida saate kohandada vastavalt oma vajadustele. Teil on võimalik mitmel erineval veebisaidil hankida tootevooge, pilte, hinda ja kõiki muid toote kohta asjakohaseid üksikasju. Selle abil saate luua oma võimsa andmebaasi hinnavõrdlussaidi jaoks.

2. Veebikraapimine R-s

Hinnavõrdlus muutub tülikaks, kuna veebiandmete hankimine pole nii lihtne - sisu levitamiseks on olemas sellised tehnoloogiad nagu HTML, XML ja JSON.

Seega peate vajalike andmete saamiseks navigeerima tõhusalt nende erinevate tehnoloogiate kaudu. R aitab teil pääseda juurde nendesse tehnoloogiatesse salvestatud andmetele. Kuid see nõuab enne alustamist R-ist veidi põhjalikku mõistmist.

Mis on 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.

Ettevaatust teile: teatud veebisaitidel on kraapimisvastased eeskirjad . Kui pingutate üle, blokeeritakse teid ja toote üksikasjade asemel näete captchasid. Muidugi saate õppida ka captchade ümber töötama, kasutades erinevaid saadaolevaid teenuseid. Siiski peate mõistma andmete kraapimise seaduslikkust ja kõike, mida te kraabitud andmetega teete.

Saada mulle julgelt oma tagasisidet ja ettepanekuid selle postituse kohta!