r - Rvest,循环浏览页面上的元素以跟踪每个元素的链接?
问题描述
所以我试图从一个包含我学校俱乐部的俱乐部数据的网站上抓取数据。我有一个很好的脚本可以从网站上抓取表面数据,但是我可以通过单击每个俱乐部的“更多信息”链接来获取更多数据,该链接指向俱乐部的个人资料页面。我想从该页面(特别是 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。但是我不知道如何制作该功能以使其正常工作。
解决方案
your error says that you are trying to combine two different dimensions... your page variable already has one dimension and second is 0. page <- html_session(url)
add this inside you function.