R Веб-парсинг на нескольких уровнях веб-сайта - PullRequest
2 голосов
/ 17 июня 2020

Я новичок в веб-парсинге R. В этом случае сначала я попытался выполнить простой парсинг с помощью R. Это работа, которую я проделал. ), это код, который я использовал,

library(rvest)
url <- read_html("https://science.kln.ac.lk/depts/im/index.php/staff/academic-staff")
url %>% html_nodes(".sppb-addon-content") %>% html_text()

Указанный выше код работает, и отображаются все отсортированные данные.

Когда вы нажимаете на каждого сотрудника, вы можете получить другую информацию, такую ​​как Исследовательские интересы, Области специализации, Профиль и т. Д. c .... Как мне получить эти данные и показать эти данные в приведенном выше наборе данных по каждому сотруднику?

1 Ответ

4 голосов
/ 17 июня 2020

Приведенный ниже код предоставит вам все ссылки на страницу каждого профессора. Оттуда вы можете сопоставить каждую ссылку с другим набором вызовов rvest, используя функции purrr map_df или map.

Связанный ответ немного отличается тем, что он отображает набор чисел, в отличие от сопоставления по вектору URL, как в приведенном ниже коде.

library(rvest)
library(purrr)
library(stringr)
library(dplyr)

url <- read_html("https://science.kln.ac.lk/depts/im/index.php/staff/academic-staff")

names <- url %>%
  html_nodes(".sppb-addon-content") %>%
  html_nodes("strong") %>%
  html_text()
#extract the names

names <- names[-c(3,4)]
#drop the head of department and blank space

names <- names %>%
  tolower() %>%
  str_extract_all("[:alnum:]+") %>%
  sapply(paste, collapse = "-")
#create a list of names separated by dashes, should be identical to link names

content <- url %>% 
  html_nodes(".sppb-addon-content") %>%
  html_text()

content <- content[! content %in% "+"]
#drop the "+" from the content

content_names <- data.frame(prof_name = names, content = content)
#make a df with the content and the names, note the prof_name column is the same as below
#this allows for joining later on

links <- url %>% 
  html_nodes(".sppb-addon-content") %>%
  html_nodes("strong") %>% 
  html_nodes("a") %>%
  html_attr("href")
#create a vector of href links

url_base <- "https://science.kln.ac.lk%s"
urls <- sprintf(url_base, links)
#create a vector of urls for the professor's pages


prof_info <- map_df(urls, function(x) {
  #create an anonymous function to pull the data

  prof_name <- gsub("https://science.kln.ac.lk/depts/im/index.php/", "", x)
  #extract the prof's name from the url

  page <- read_html(x)
  #read each page in the urls vector

  sections <- page %>%
    html_nodes(".sppb-panel-title") %>%
    html_text()
  #extract the section title

  info <- page %>%
    html_nodes(".sppb-panel-body") %>%
    html_nodes(".sppb-addon-content") %>%
    html_text()
  #extract the info from each section

  data.frame(sections = sections, info = info, prof_name = prof_name)
  #create a dataframe with the section titles as the column headers and the
  #info as the data in the columns

}) 
#note this returns a dataframe. Change map_df to map if you want a list
#of tibbles instead

prof_info <- inner_join(content_names, prof_info, by = "prof_name")
#joining the content from the first page to all the individual pages

Не уверен, что это самый чистый или самый эффективный способ сделать это, но я думаю, это то, что вам нужно.

...