【问题标题】:Error: invalid subscript type 'list' (Webscraping)错误:无效的下标类型“列表”(Webscraping)
【发布时间】:2019-02-04 11:12:29
【问题描述】:

我正在尝试从以下网址抓取数据: 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)

#Reading the each url
library(purrr)    
allreadurls<-map(allcollegeurls$url, read_html)

到目前为止工作正常,但是当我编写以下代码时,它显示错误。

#Specialization
#Using CSS selectors to scrap the specialization section
allcollegeurls$Specialization<-NA
for (i in allreadurls) {
  allcollegeurls$Specialization[i] <- html_nodes(allreadurls[i][],'td:nth- 
  child(1)')
}

Error in allreadurls[i] : invalid subscript type 'list'

【问题讨论】:

    标签: r list web-scraping


    【解决方案1】:

    我不确定抓取的内容本身,但您可能希望将循环替换为

    for (i in 1:length(allreadurls)) {
      allcollegeurls$Specialization[i] <- html_nodes(allreadurls[i][],'td:nth-child(1)')
    }
    

    您的方法的一个问题是i 的角色不一致:它在allreadurls 中取值,但随后用于子集Specializationallreadurls。另一个问题是

    'td:nth- 
      child(1)'
    

    最后,由于allreadurls 是一个列表,您希望使用[[i]] 对其进行子集化,而不是[i](它再次返回一个列表)。最后,不需要[]

    【讨论】:

      猜你喜欢
      • 2017-10-05
      • 2015-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-06
      • 2017-09-27
      • 1970-01-01
      相关资源
      最近更新 更多