【发布时间】:2019-02-04 09:31:06
【问题描述】:
我正在尝试从以下网址抓取数据: https://university.careers360.com/colleges/list-of-degree-colleges-in-India 我想点击每所大学的名称并获取每所大学的特定数据。
首先我所做的是将所有大学网址收集在一个向量中-:
#loading the package:
library(xml2)
library(rvest)
library(stringr)
library(dplyr)
#Specifying the url for desired website to be scrapped
baseurl <- "https://university.careers360.com/colleges/list-of-degree-colleges-in-India"
#Reading the html content from Amazon
basewebpage <- read_html(baseurl)
#Extracting college name and its url
scraplinks <- function(url){
#Create an html document from the url
webpage <- xml2::read_html(url)
#Extract the URLs
url_ <- webpage %>%
rvest::html_nodes(".title a") %>%
rvest::html_attr("href")
#Extract the link text
link_ <- webpage %>%
rvest::html_nodes(".title a") %>%
rvest::html_text()
return(data_frame(link = link_, url = url_))
}
#College names and Urls
allcollegeurls<-scraplinks(baseurl)
到目前为止工作正常,但是当我对每个 url 使用 read_html 时,它会显示错误。
#Reading the each url
for (i in allcollegeurls$url) {
clgwebpage <- read_html(allcollegeurls$url[i])
}
错误:当前工作目录(“C:/Users/User/Documents”)中不存在“NA”。
我什至使用了'break'命令但仍然是同样的错误-:
#Reading the each url
for (i in allcollegeurls$url) {
clgwebpage <- read_html(allcollegeurls$url[i])
if(is.na(allcollegeurls$url[i]))break
}
请帮忙。
按要求发布所有大学网址的str-:
> str(allcollegeurls)
Classes ‘tbl_df’, ‘tbl’ and 'data.frame': 30 obs. of 2 variables:
$ link: chr "Netaji Subhas Institute of Technology, Delhi" "Hansraj
College, Delhi" "School of Business, University of Petroleum and Energy
Studies, D.." "Hindu College, Delhi" ...
$ url : chr "https://www.careers360.com/university/netaji-subhas-
university-of-technology-new-delhi"
"https://www.careers360.com/colleges/hansraj-college-delhi"
"https://www.careers360.com/colleges/school-of-business-university-of-
petroleum-and-energy-studies-dehradun"
"https://www.careers360.com/colleges/hindu-college-delhi" ...
【问题讨论】:
-
我是 R 新手,所以请相应地解释一下。提前致谢。
-
allcollegeurls有url列吗?没有运行代码,因为我不确定抓取这个网站的法律含义。可以加一下 allcollegeurls 的str吗? -
是的,它有一个 url 列!刚刚写了结构
标签: r web-scraping na