【问题标题】:How to web scrape data from a separate page that each element has in rvest?如何从每个元素在 rvest 中的单独页面中抓取数据?
【发布时间】:2018-08-14 05:38:27
【问题描述】:

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

我尝试获取 facebook 页面的部分在这里:

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

  df$fb <- html_node(sub_page, "#dnf_class_values_student_group__facebook__widget") %>% html_text()

但是,这会返回错误。我究竟做错了什么?有没有办法从每个俱乐部的单独页面中抓取数据?

【问题讨论】:

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


    【解决方案1】:

    使用 xpath 根据其 id 提取所需节点。

    df$fb <- html_node(sub_page, xpath = '//*[@id="dnf_class_values_student_group__facebook__widget"]') %>% html_text()
    
    # > html_node(sub_page, xpath = '//*[@id="dnf_class_values_student_group__facebook__widget"]') %>% html_text()
      # [1] "https://www.facebook.com/17thavehouse/?fref=ts"
    

    但是,您需要“循环”浏览所有 df$name_text 以打开所有不同的子页面并提取 facebook 链接。

    【讨论】:

    • 除了我的递归循环之外,我如何循环遍历这个?
    • @ConnorCarlson 你(例如)写一个你用 (m)apply 调用的自定义函数。请提出一个单独的问题,如果对您有帮助,请接受我的回答。
    猜你喜欢
    • 2016-10-05
    • 2018-03-20
    • 1970-01-01
    • 2019-02-16
    • 1970-01-01
    • 2019-06-24
    • 2011-03-01
    • 1970-01-01
    • 2014-11-20
    相关资源
    最近更新 更多