Извлечение таблицы из JavaScript веб-страницы - PullRequest
3 голосов
/ 05 января 2020

Я хочу извлечь таблицу на вкладке Option Chain следующей веб-страницы, используя R -

https://nseindia.com/get-quotes/derivatives?symbol=SBIN

Webpage snapshot

Я пытаюсь использовать rvest для этой цели, однако стандартный способ извлечения таблиц из простых веб-страниц на основе html, похоже, не работает.

Вот то, что я пытаюсь -

library('rvest')
x <- c('https://nseindia.com/get-quotes/derivatives?symbol=SBIN')
url <- paste(x,collapse="")
webpage <- read_html(url)
data <- webpage %>% html_nodes(xpath = '//*[@id="optionChainTable-equity"]') %>% html_table()

Это возвращает пустой список. Что мне не хватает?

1 Ответ

3 голосов
/ 05 января 2020

Данные, которые вы ищете, загружаются динамически как JSON с другого URL. Кроме того, мне кажется, что мне нужно сменить пользовательский агент, чтобы получить данные, иначе сервер откажется от соединения.

Как только он у вас есть, вам нужно проанализировать JSON с такой библиотекой, как jsonlite. В этом примере я преобразовал данные в таблицу, чтобы их было легче увидеть в консоли.

library(httr)
library(jsonlite)
library(tibble)

user_agent    <-  paste("Mozilla/5.0 (Windows NT 6.1;",
                         "rv =61.0) Gecko/20100101 Firefox/61.0");

accept_string <-  paste0("text/html,application/xhtml+xml,",
                          "application/xml;q=0.9,*/*;q=0.8");

headers       <- add_headers( `User-Agent`                = user_agent,
                              Accept                      = accept_string,
                              `Accept-Language`           = "en-GB,en;q=0.5",
                              `Accept-Encoding`           = "gzip, deflate",
                              Connection                  = "keep-alive",
                              `Upgrade-Insecure-Requests` = "1");

url <- "https://nseindia.com/api/option-chain-equities?symbol=SBIN"
table_contents <- content(GET(url, config = headers), "text")
df <- as_tibble(fromJSON(table_contents)$`records`$data)

df
# A tibble: 89 x 4
#>    strikePrice expiryDate PE$strikePrice $expiryDate $underlying $identifier
#>          <int> <chr>               <int> <chr>       <chr>       <chr>
#>  1         210 30-Jan-20~            210 30-Jan-2020 SBIN        OPTSTKSBIN~
#>  2         215 30-Jan-20~            215 30-Jan-2020 SBIN        OPTSTKSBIN~
#>  3         220 30-Jan-20~            220 30-Jan-2020 SBIN        OPTSTKSBIN~
#>  4         225 30-Jan-20~            225 30-Jan-2020 SBIN        OPTSTKSBIN~
#>  5         230 30-Jan-20~            230 30-Jan-2020 SBIN        OPTSTKSBIN~
#>  6         235 30-Jan-20~            235 30-Jan-2020 SBIN        OPTSTKSBIN~
#>  7         240 30-Jan-20~            240 30-Jan-2020 SBIN        OPTSTKSBIN~
#>  8         245 30-Jan-20~            245 30-Jan-2020 SBIN        OPTSTKSBIN~
#>  9         250 27-Feb-20~            250 27-Feb-2020 SBIN        OPTSTKSBIN~
#> 10         250 26-Mar-20~            250 26-Mar-2020 SBIN        OPTSTKSBIN~
# ... with 79 more rows, and 34 more variables: $openInterest <int>,
#   $changeinOpenInterest <int>, $pchangeinOpenInterest <dbl>,
#   $totalTradedVolume <int>, $impliedVolatility <dbl>, $lastPrice <dbl>,
#   $change <dbl>, $pChange <dbl>, $totalBuyQuantity <int>,
#   $totalSellQuantity <int>, $bidQty <int>, $bidprice <dbl>, $askQty <int>,
#   $askPrice <dbl>, $underlyingValue <int>, CE$strikePrice <int>,
#   $expiryDate <chr>, $underlying <chr>, $identifier <chr>, $openInterest <int>,
#   $changeinOpenInterest <int>, $pchangeinOpenInterest <dbl>,
#   $totalTradedVolume <int>, $impliedVolatility <dbl>, $lastPrice <dbl>,
#   $change <dbl>, $pChange <dbl>, $totalBuyQuantity <int>,
#   $totalSellQuantity <int>, $bidQty <int>, $bidprice <dbl>, $askQty <int>,
#   $askPrice <dbl>, $underlyingValue <int>
...