Thành viên:Vinhtantran/Scrape code

Bách khoa toàn thư mở Wikipedia

Trang này lưu trữ lại những mã nguồn tôi dùng để trích xuất dữ liệu từ Internet để viết bài, tạo bảng biểu, hoặc vẽ đồ thị trên Wikipedia tiếng Việt. Tất nhiên, những nội dung đã được đăng thì sẽ tuân theo quy định giấy phép của Wikipedia, bao gồm Creative Commons Ghi công–Chia sẻ tương tự phiên bản 3.0 Chưa chuyển đổiGFDL.

Danh sách Đại biểu Quốc hội Khóa XIV[sửa | sửa mã nguồn]

Các bước:

  1. Sau khi lấy dữ liệu thô từ trang web về, dữ liệu sẽ được dọn dẹp và phân tách để tạo ra cú pháp Wiki (liên kết, sắp xếp), sau đó xuất thành tập tin .csv
  2. Dữ liệu được đọc vào lại để áp dụng mã wiki để nhập các cột thuộc cùng một tỉnh với nhau, sau đó xuất thành tập tin .csv
  3. Sử dụng công cụ CSV Converter để chuyển nội dung file CSV thành bảng wiki
  4. Thêm class="wikitable sortable" và header vào bảng

Bước 1[sửa | sửa mã nguồn]

library(rvest)
library(tidyverse)

# Scrape
PAGES <- 13
daibieu <- vector("list", PAGES)
for (page in 1:13) {
  url <- read_html(str_c("http://hoidongbaucu.quochoi.vn/bau-cu-quoc-hoi/khoa-xiv/Pages/danh-sach-nguoi-trung-cu.aspx?NoiUngCu=0&NoiDeCu=0&LoaiDaiBieu=0&DanToc=0&GioiTinh=0&order=Ten&TypeOfOrder=True&Page=", page), encoding = "UTF-8")

  daibieu.p <- html_nodes(x = url, xpath = "//*[@id=\"PopupVanBanSearchAdvance\"]/div/div[3]/div/div/div/table") %>%
    html_table(header = TRUE)

  daibieu[[page]] <- as.tibble(daibieu.p[[1]])
}

# Save the file to avoid scraping every time it needs fixing
write_excel_csv(bind_rows(daibieu) %>%
  rename(fullname = "Họ tên",
         bd = "Ngày sinh",
         sex = "Giới tính",
         place = 5,
         rate = 6,
         results = 7) %>%
  # The case of two M'Nong and K'Ho names
  mutate(fullname = str_replace_all(fullname, "`|’ ", "'")), "daibieu_raw.csv")

### START HERE
daibieu.lst <- read_csv("daibieu_raw.csv")

# Remove names that were resigned/dead/removed/dismissed
# ă: \u0103, Đ: \u0110, ư: \u01B0
daibieu.lst <- daibieu.lst %>%
  filter(!(fullname %in% c("Trịnh Xuân Thanh",
                          "Nguyễn Thị Nguyệt H\u01B0ờng",
                          "Ngô V\u0103n Minh",
                          "Nguyễn Hội",
                          "Võ Kim Cự",
                          "\u0110inh La Th\u0103ng",
                          "Nguyễn Quốc Khánh",
                          "Ngô \u0110ức Mạnh",
                          "Phan Thị Mỹ Thanh",
                          "Lê Minh Thông",
                          "Trần \u0110ại Quang")))

# Check for the longest name
nwords <- daibieu.lst %>%
  mutate(nospace = gsub(" ", "", fullname),
         nword = nchar(fullname) - nchar(nospace) + 1) %>%
  select(nword)

longestname <- max(nwords$nword)

names <- paste0("T", longestname:1)
  
final <- daibieu.lst %>% 
  extract(bd, c("d", "m", "y"), "(\\d*)/(\\d*)/(\\d*)") %>%
  # extract(fullname, c("H", "T"), "(\\X*) (\\X*)") %>%
  separate(fullname, names, sep = "\\ ", remove = F, fill = "left") %>%
  mutate_at(names, funs(replace(., is.na(.), ""))) %>%
  # extract(fullname, c("H", "T"), "([^ ]+) ?(.*)") %>%
  # extract(T, c("TL", "T"), "(.*) (.*)") %>%
  unite(sort, rev(names), sep = ",", remove = FALSE) %>%
  mutate(newName = paste0("data-sort-value=\"", sort,
                          "\"|[[", fullname, "]]"),
         newBD = paste0("{{ngày sinh và tuổi|", y, "|", m, "|", d, "}}")) %>%
  mutate(since = "", position = "") %>%
  arrange(place, T1, T2) %>%
  select(place, newName, newBD, sex, position, since)

# Put links at province names
prov <- final$place
keep <- match(unique(prov), prov)

# Remove "TP" from names and wikilink
prov.notp <- gsub(prov, pattern = "TP ", replacement = "")
prov.notp <- gsub(prov.notp, pattern = "Hồ Chí Minh", replacement = "Thành phố Hồ Chí Minh|TP Hồ Chí Minh")

final$place[keep] <- str_c("rowspan = ", table(prov.notp)[prov.notp[keep]], "|[[", prov.notp[keep], "]]")

# Rename the columns
final <- final %>%
  rename("Tỉnh thành" = 1, "Họ tên" = 2, "Ngày sinh" = 3, "Giới tính" = 4, 
         "Chức vụ" = 5, "Đại biểu từ" = 6)

# Write the data file
write_excel_csv(final, "dbqh14_notmerged.csv", na = "")

Bước 2[sửa | sửa mã nguồn]

provlist <- unique(prov)
dbqh_list <- read_file("dbqh14_notmerged.csv")
dbqh_list_merged <- str_replace_all(dbqh_list, 
                                    paste(str_c(provlist, ","), collapse = "|"),
                                    "")


write_file(dbqh_list_merged, path = "dbqh14_merged.csv")