install.packages("rvest")
## The following package(s) will be installed:
## - rvest [1.0.3]
## These packages will be installed into "D:/DaiHoc/nam3/R/doan/WebScraping_with_R/WebScrapingFinal/renv/library/R-4.3/x86_64-w64-mingw32".
## 
## # Installing packages --------------------------------------------------------
## - Installing rvest ...                          OK [copied from cache in 0.24s]
## Successfully installed 1 package in 0.26 seconds.
library(rvest)
library(stringr)
library(DBI)

PHẦN 1 CÀO DỮ LIỆU

Lấy nội dung HTML của đường URL cung cấp

url <- "https://www.thegioididong.com/dtdd#c=42&o=17&pi=4"

resp <- read_html(url)
resp
## {html_document}
## <html lang="vi-VN">
## [1] <head>\n<meta http-equiv="Content-Type" content="text/html; charset=UTF-8 ...
## [2] <body class="">\n    \n<div class="header-top-bar">\n        <div class=" ...

Lấy danh sách các tag “li” chứa mẫu điện thoại

items <- html_nodes(resp, css=".listproduct") %>% html_nodes(".item.ajaxed.__cate_42")
items[1:5]
## {xml_nodeset (5)}
## [1] <li class=" item ajaxed __cate_42" data-index="1" data-id="305658" data-i ...
## [2] <li class=" item ajaxed __cate_42" data-index="2" data-id="299033" data-i ...
## [3] <li class=" item ajaxed __cate_42" data-index="3" data-id="303891" data-i ...
## [4] <li class=" item ajaxed __cate_42" data-index="4" data-id="281570" data-i ...
## [5] <li class=" item ajaxed __cate_42" data-index="5" data-id="313199" data-i ...

y

#Data frame
phone_df <- data.frame(stringsAsFactors = FALSE)
# Điện thoại

for (item in items) {
  # Tên sản phẩm
  names <- html_node(item, "h3") %>% html_text()
  
  # Kích thước screen và công nghệ screen
  features <- html_node(item, ".item-compare") %>% html_elements("span") %>% html_text()
  for (idx in 1:2) {
    if (idx %% 2 != 0)
      screen_size <- features[idx]
    else
      screen_tech <- features[idx]
  }
  
  # Giá cũ
  old_prices <- html_node(item, ".price-old") %>% html_text()
  
  # Giá hiện tại
  current_prices <- html_node(item, ".price") %>% html_text()
  
  # GIảm giá
  discounts <- html_node(item, ".percent") %>% html_text()
  
  #Đánh giá
  ratings <- html_node(item, ".item-rating-total") %>% html_text()
  
  #Dung lương
  storages <- html_node(item, ".prods-group") %>% html_node(".merge__item.item.act") %>% html_text(trim=TRUE)
  
  #Loại
  genres <- "Điện thoại"
  
  # Thêm dòng 1 sp vào dataframe
  phone_df <- rbind(phone_df, data.frame(names, genres, screen_size, screen_tech, old_prices, current_prices, discounts, ratings, storages, stringsAsFactors = FALSE))
  
  
}

phone_df

Dữ liệu Laptop

url <- "https://www.thegioididong.com/laptop?g=laptop-gaming"

resp <- read_html(url)
resp
## {html_document}
## <html lang="vi-VN">
## [1] <head>\n<meta http-equiv="Content-Type" content="text/html; charset=UTF-8 ...
## [2] <body class="">\n    \n<div class="header-top-bar">\n        <div class=" ...
items <- html_nodes(resp, css=".listproduct") %>% html_nodes(".item.__cate_44")
items[1:5]
## {xml_nodeset (5)}
## [1] <li class=" item  __cate_44" data-index="1" data-id="304867" data-issetup ...
## [2] <li class=" item  __cate_44" data-index="2" data-id="303500" data-issetup ...
## [3] <li class=" item  __cate_44" data-index="3" data-id="263983" data-issetup ...
## [4] <li class=" item  __cate_44" data-index="4" data-id="306133" data-issetup ...
## [5] <li class=" item  __cate_44" data-index="5" data-id="313251" data-issetup ...
for (item in items) {
  # Tên sản phẩm
  names <- html_node(item, "h3") %>% html_text()
  
  # Kích thước screen và công nghệ screen
  features <- html_node(item, ".utility") %>% html_element("p") %>% html_text()
  features <- as.vector(str_split_fixed(features, pattern = ",", n = 3))
  for (idx in 1:2) {
    if (idx %% 2 != 0)
      screen_size <- features[idx]
    else
      screen_tech <- features[idx]
  }
  
  # Giá cũ
  old_prices <- html_node(item, ".price-old") %>% html_text()
  
  # Giá hiện tại
  current_prices <- html_node(item, ".price") %>% html_text()
  
  # GIảm giá
  discounts <- html_node(item, ".percent") %>% html_text()
  
  #Đánh giá
  ratings <- html_node(item, ".item-rating-total") %>% html_text()

  #Dung lương
  temp <- html_nodes(item, ".item-compare") %>% html_nodes("span") %>% html_text()
  storages <- temp[2]
  
  #Loại
  genres <- "Laptop gamming"
  
  # Thêm dòng 1 sp vào dataframe
  phone_df <- rbind(phone_df, data.frame(names, genres, screen_size, screen_tech, old_prices, current_prices, discounts, ratings, storages, stringsAsFactors = FALSE))
  
}
phone_df

PHẦN 2 XỬ LÍ DỮ LIỆU

BƯỚC 1 Khai báo thư viện

install.packages("dplyr")
## The following package(s) will be installed:
## - dplyr [1.1.3]
## These packages will be installed into "D:/DaiHoc/nam3/R/doan/WebScraping_with_R/WebScrapingFinal/renv/library/R-4.3/x86_64-w64-mingw32".
## 
## # Installing packages --------------------------------------------------------
## - Installing dplyr ...                          OK [copied from cache in 0.34s]
## Successfully installed 1 package in 0.36 seconds.
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union

Bước 2:Xem tên cột và copy dữ liệu dataframe

data_copy <- data.frame(phone_df)
#xem tên cột
name<-colnames(data_copy)
name
## [1] "names"          "genres"         "screen_size"    "screen_tech"   
## [5] "old_prices"     "current_prices" "discounts"      "ratings"       
## [9] "storages"

Xem kiễu liệu của dataframe

#xem tổng quan về df
str(data_copy)
## 'data.frame':    40 obs. of  9 variables:
##  $ names         : chr  "\n            iPhone 15 Pro Max\n        " "\n            iPhone 15 Pro\n        " "\n            iPhone 15 Plus\n        " "\n            iPhone 15\n        " ...
##  $ genres        : chr  "Điện thoại" "Điện thoại" "Điện thoại" "Điện thoại" ...
##  $ screen_size   : chr  "6.7\"" "6.1\"" "6.7\"" "6.1\"" ...
##  $ screen_tech   : chr  "Super Retina XDR" "Super Retina XDR" "Super Retina XDR" "Super Retina XDR" ...
##  $ old_prices    : chr  NA "28.990.000₫" "25.990.000₫" "22.990.000₫" ...
##  $ current_prices: chr  "34.990.000₫" "27.990.000₫" "24.990.000₫" "21.990.000₫" ...
##  $ discounts     : chr  NA "-3%" "-3%" "-4%" ...
##  $ ratings       : chr  NA NA NA NA ...
##  $ storages      : chr  "256GB" "128GB" "128GB" "128GB" ...

Bước 3:Làm sạch và định đạng dữ liệu

#coverting the blank spaces into NA
columns <- colnames(data_copy)
for (column in columns) {
  data_copy[[column]] <- ifelse(trimws(data_copy[[column]]) == "", NA, data_copy[[column]])
}
data_copy

Bước 4:Xử lí các giá trị bị thiếu

Bước 4.1:Xem giá trị na trong từng cột

  # Seeing missing values 
  colSums(is.na(data_copy))
##          names         genres    screen_size    screen_tech     old_prices 
##              0              0              0              0              4 
## current_prices      discounts        ratings       storages 
##              0              4             11              2

Bước 4.2 Xử lí giá trị na

input<-2

  #Cách 1 :Xử lí giá trị na bằng cách xóa bỏ hàng na
if(input==1)
{
 # Xóa hàng có giá trị na 
   data_copy<-na.omit(data_copy)
   data_copy
}else
{
  #Cách 2:Xử lí Na bằng cách điền giá trị phổ biến
  most_common_values <- list()
  for (col in columns) {
  # Đếm số lần giá trị xuất hiện
  frequency <- table(data_copy[[col]])
  # Tìm giá trị phổ biến
  mostcom <- (names(frequency)[which.max(frequency)])
  # Lưu giá trị phổ biến vào danh sách
  most_common_values[[col]] <- mostcom
  # Điền giá trị phổ biến vào các ô NA trong cột
  data_copy[[col]][is.na(data_copy[[col]])] <- mostcom
}

data_copy
}

Bước 5 :Chuyển đổi dữ liệu từ chuỗi sang số cho phù hợp

#chuyển đổi rating 
data_copy$ratings<-as.integer(data_copy$ratings)

#chuyển đổi old_prices
data_copy$old_prices<- gsub("₫", "", data_copy$old_prices)
data_copy$old_prices <- gsub("\\.", "", data_copy$old_prices)
data_copy$old_prices<-as.double(data_copy$old_prices)

# chuyển đổi current_prices
data_copy$current_prices <- gsub("₫", "", data_copy$current_prices)
data_copy$current_prices <- gsub("\\.", "", data_copy$current_prices)
data_copy$current_prices<-as.double(data_copy$current_prices)

#chuyển đổi discounts
data_copy$discounts <- gsub("%", "", data_copy$discounts)
data_copy$discounts <- gsub("\\-", "", data_copy$discounts)

#bỏ kí tự \n
data_copy$names<-gsub("\n","",data_copy$names)
data_copy$discounts<-as.double(data_copy$discounts)
data_copy

Bước 6 Xử lí giá trị cá biệt Vẽ Biểu Đồ Zscore

# Lọc ra các cột số từ dataframe
df_numeric <- data_copy %>%
  select(old_prices, current_prices, discounts, ratings)

# Tính z-score cho từng cột
df_zscore <- df_numeric %>%
  mutate_all(function(x) (x - mean(x, na.rm = TRUE)) / sd(x, na.rm = TRUE))

# Vẽ biểu đồ z-score cho từng cột
par(mfrow=c(2,2))  # Tạo một lưới 2x2 để vẽ 4 biểu đồ
for (col in colnames(df_zscore)) {
  hist(df_zscore[[col]], main = paste("Z-Score for", col), xlab = "Z-Score")
}

Dựa trên biểu đồ chọn zscore ngưỡng

# Đặt ngưỡng z-score bạn muốn sử dụng
nguong_z_score <- 4  # Ví dụ: Chọn ngưỡng z-score ±4

# Loại bỏ các dòng có z-score nằm ngoài ngưỡng
df_cleaned <- data_copy
for (col in colnames(df_zscore)) {
  df_cleaned <- df_cleaned[abs(df_zscore[[col]]) <= nguong_z_score, ]
}
df_cleaned

Phần 3: DATABASE

Bước 1: cai library DBI, odbc

library(DBI) 
library(odbc) 
library(RODBC) 

Bước 2: Chuỗi kết nối đến SQL Server LocalDB

connection_string <- "Driver={ODBC Driver 17 for SQL Server};Server=(localdb)\\MSSQLLocalDB;Trusted_Connection=Yes;" 

Bước 3: Tạo kết nối

con <- dbConnect(odbc(), .connection_string = connection_string) 

Bước 4: Thực hiện một truy vấn SQL để tạo bảng (nếu bảng chưa tồn tại) #Tạo database

tryCatch(
  {
    sql_create_db <- "CREATE DATABASE WebScraper" 
    dbGetQuery(conn = con, sql_create_db) 
  },error = function(e) 
  {
    cat("Đã Tồn Tại Database")
  }
)
## Đã Tồn Tại Database

Tạo table

colSums(is.na(data_copy))
##          names         genres    screen_size    screen_tech     old_prices 
##              0              0              0              0              0 
## current_prices      discounts        ratings       storages 
##              0              0              0              0
#tạo bảng 
create_table_sql <- " USE WebScraper IF OBJECT_ID (N'dbo.WebScraping_Table', N'U') IS NOT NULL 
                      DROP TABLE dbo.WebScraping_Table; 

                      CREATE TABLE WebScraping_Table ( 
                      Id INT IDENTITY(1, 1) NOT NULL, 
                      names NVARCHAR(255),
                      genres NVARCHAR(255), 
                      screen_size VARCHAR(255), 
                      screen_tech NVARCHAR(255), 
                      old_prices NUMERIC, 
                      current_prices NUMERIC, 
                      discounts NUMERIC,
                      ratings NUMERIC, 
                      storages NVARCHAR(255) 
                      ) 
" 
dbGetQuery(conn = con, create_table_sql) 

Bước 5: Store DATA

dbWriteTable(conn = con, "WebScraping_Table", data_copy, overwrite = FALSE, append = TRUE) 

Bước 6: Read Data

loadData <- dbReadTable(con, "WebScraping_Table", row.names = FALSE) 
loadData

Bước end: Đóng kết nối

dbDisconnect(con)