R中的数据网络抓取

时间:2017-09-13 05:32:32

标签: r web-scraping rvest

使用R和rvest从www.nseindia.com抓取网页数据。我第一次能够下载数据,但之后出现以下错误消息......

UseMethod(“xml_find_all”)中的错误:   没有适用于'xml_find_all'的方法适用于类“character”的对象

我试图获得索引未来的第一行

我的代码如下

    library("rvest")

    website_nifty_future_live<- read_html("https://www.nseindia.com/live_market/dynaContent/live_watch/fomwatchsymbol.jsp?key=NIFTY&Fut_Opt=Futures")

    nifty_spot<- website_nifty_future_live %>%
      + html_nodes(".alt:nth-child(2) td:nth-child(13)") %>%
       + html_text()
    nifty_spot<-as.numeric(gsub(",","",nifty_spot))

1 个答案:

答案 0 :(得分:0)

错误很可能是由于&#34; +&#34;在代码开头的标志 - 删除它时我没有收到此错误。

我建议使用以下代码将整个表读作data.frame:

library("rvest")

url_nifty <- "https://www.nseindia.com/live_market/dynaContent/live_watch/fomwatchsymbol.jsp?key=NIFTY&Fut_Opt=Futures"
website_nifty_future_live<- read_html(url_nifty)

nifty_spot<- website_nifty_future_live %>%
   html_nodes("#tab26Content > table:nth-child(1)") %>%
   html_table(header = NA, trim = TRUE, fill = FALSE, dec = ".") %>%
   as.data.frame()

然后当然很容易得到第一行包括。标题,例如与

nifty_spot[1, ]
     Instrument Underlying Expiry.Date Option.Type Strike.Price Open.Price High.Price Low.Price Prev..Close Last.Price Volume Turnover.lacs.
1 Index Futures      NIFTY   28SEP2017           -            -  10,105.00  10,144.70 10,078.00   10,107.90  10,096.90 94,799    7,18,943.53
  Underlying..Value
1           10079.3

希望它有所帮助!

相关问题