我想使用 R 提取以下网页的“期权链”选项卡下的表格 -
https://nseindia.com/get-quotes/derivatives?symbol=SBIN
我正在尝试使用 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()
这将返回一个空列表。我缺少什么?
最佳答案
您正在查找的数据会从不同的 url 以 JSON 形式动态加载。另外,我似乎需要更改用户代理来获取数据,否则服务器会拒绝连接。
一旦获得它,您需要使用像 jsonlite 这样的库来解析 JSON。在此示例中,我已将数据转换为 tibble,以便更容易在控制台中查看。
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>
关于javascript - 从基于 JavaScript 的网页中提取表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59601273/