Rvest,循环浏览页面上的元素以跟踪每个元素的链接?

问题描述 投票:0回答:2

所以我试图从一个包含我学校俱乐部俱乐部数据的网站上搜索数据。我有一个好的剧本可以从网站上删除表面级别的数据,但是我可以通过点击每个俱乐部的“更多信息”链接获得更多数据,这些链接指向俱乐部的个人资料页面。我想从该页面(特别是facebook链接)中删除数据。

下面你会看到我目前的尝试。

url <- 'https://uws-community.symplicity.com/index.php?s=student_group'
page <- html_session(url)

get_table <- function(page, count) {
  #find group names
  name_text <- html_nodes(page,".grpl-name a") %>% html_text()
  df <- data.frame(name_text, stringsAsFactors = FALSE)

  #find text description
  desc_text <- html_nodes(page, ".grpl-purpose") %>% html_text()
  df$desc_text <- trimws(desc_text)

  #find emails
  #  find the parent nodes with html_nodes
  #  then find the contact information from each parent using html_node
  email_nodes<-html_nodes(page, "div.grpl-grp") %>% html_node( ".grpl-contact a") %>% html_text()
  df$emails<-email_nodes

  category_nodes <- html_nodes(page, "div.grpl-grp") %>% html_node(".grpl-type") %>% html_text()
  df$category<-category_nodes

  pic_nodes <-html_nodes(page, "div.grpl-grp") %>% html_node( ".grpl-logo img") %>% html_attr("src")
  df$logo <- paste0("https://uws-community.symplicity.com/", pic_nodes)

  more_info_nodes <- html_nodes(page, ".grpl-moreinfo a") %>% html_attr("href")
  df$more_info <- paste0("https://uws-community.symplicity.com/", more_info_nodes)

  sub_page <- page %>% follow_link(css = ".grpl-moreinfo a")

  df$fb <- html_node(sub_page, xpath = '//*[@id="dnf_class_values_student_group__facebook__widget"]') %>% html_text()

  if(count != 44) {
    return (rbind(df, get_table(page %>% follow_link(css = ".paging_nav a:last-child"), count + 1)))
  } else{
    return (df)
  }
}


RSO_data <- get_table(page, 0)

我得到的当前错误是:

Error in `$<-.data.frame`(`*tmp*`, "logo", value = "https://uws-community.symplicity.com/") : 
  replacement has 1 row, data has 0 

我知道我需要创建一个函数来遍历每个元素并按照链接,然后将该函数映射到数据帧df。但是,我不知道如何制作该功能以使其正常工作。

r database web-scraping data-science rvest
2个回答
1
投票

你的错误说你正在尝试组合两个不同的维度...你的页面变量已经有一个维度,第二个是0.page <- html_session(url)在你的函数中添加这个。


0
投票

这是您的错误消息的可重现示例。

x = data.frame()
x[1] <- c(1)

我没有检查你的代码,但错误就在那里,你必须逐步完成你的代码。您将找到错误,您在其中创建了一个空的data.frame,然后尝试为其分配值。祝好运

© www.soinside.com 2019 - 2024. All rights reserved.