【问题标题】:rvest, following a link present on each node to get more data?rvest,按照每个节点上的链接获取更多数据?
【发布时间】:2018-08-20 03:45:25
【问题描述】:

所以我试图从一个包含我学校俱乐部的俱乐部数据的网站上抓取数据。我有一个很好的脚本可以从网站上抓取表面数据,但是我可以通过单击每个俱乐部的“更多信息”链接来获取更多数据,该链接指向俱乐部的个人资料页面。我想从该页面(特别是 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 将其应用于页面上的元素数量

有没有更好的方法来做到这一点?我做错了什么?

【问题讨论】:

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


    【解决方案1】:

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

    在第 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))
    }
    

    我不会推荐它,但这是可能的。

    【讨论】:

    • 我正在使用 + 将函数参数插入到 follow_link 函数中,有没有更好的方法来做到这一点?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    • 2018-08-26
    • 2017-09-09
    • 2020-02-25
    • 2018-07-19
    • 1970-01-01
    相关资源
    最近更新 更多