rvest,遵循每个节点上存在的链接以获取更多数据吗?

时间:2018-08-20 03:45:25

标签: r database web-scraping data-science rvest

因此,我正在尝试从一个包含我学校俱乐部数据的站点中收集数据。我有一个很好的脚本,可以从站点上抓取表面水平面数据,但是,我可以通过单击每个俱乐部的“更多信息”链接(指向俱乐部的个人资料页面)来获得更多数据。我想从该页面(特别是facebook链接)中抓取数据。

在下面,您将看到我目前的尝试。

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

get_more_info <- function(position) {
  page <- follow_link(page, css = ".grpl-moreinfo > a:nth-child(" + position + ")")
  html_node(sub_page, xpath = '//*[@id="dnf_class_values_student_group__facebook__widget"]') %>% html_text()
  page <- page %>% back()
}

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)

  df$fb <- lapply(1:nrow(df), get_more_info)

  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 ".grpl-moreinfo > a:nth-child(" + position : 
  non-numeric argument to binary operator

如您所见,我正在尝试通过使用“ get_more__data”函数并使用lapply将其应用于页面上的元素数量来跟踪每个元素上的链接

有更好的方法吗?我在做什么错了?

1 个答案:

答案 0 :(得分:0)

我认为您的解决方案比您想象的要容易得多。

您在第4行中使用了

  page <- follow_link(page, css = ".grpl-moreinfo > a:nth-child(" + position + ")")

其中

css = ".grpl-moreinfo > a:nth-child(" + position + ")"

在R中,您不会将字符串与“ +”连接起来,即,使用

无效
"He" + "llo"

使用paste('He', 'llo', sep = '')paste0('He', 'llo')

重试一次

请下次尝试查看错误消息本身。它经常告诉您错误的确切来源。

编辑:

如果要像在Python中那样使用它,可以编写自己的函数,如下所示:

`+` <- function(x, y){
  return(paste0(x, y))
}

我不推荐,但是有可能。