Rvest 不会 return 数据

Rvest wont return data

我一直在尝试抓取以下内容 table:

您的问题是您的请求为您提供了一个 html 站点,而不是 json 响应。因此,将其解析为 json 失败并出现您看到的错误。
(我不能确切地告诉你这是因为你错过了 accept_json() 还是因为你使用的 URL 有点不对。)。

无论哪种方式,逆向工程 API 请求背后的 table 请求的要点,你必须将这样的东西放在一起:

require(httr)
require(dplyr)
library(purrr)

first_req <- GET("https://www.barchart.com")
xsrf_token <- cookies(first_req) %>% filter(name == 'XSRF-TOKEN') %>% pull(value) %>% URLdecode()

req <- GET(
    "https://www.barchart.com/proxies/core-api/v1/quotes/get",
    query = list(
      lists = "stocks.optionable.by_sector.all.us",
      fields = "symbol,symbolName,lastPrice,priceChange,percentChange,highPrice,lowPrice,volume,tradeTime,symbolCode,symbolType,hasOptions",
      orderBy = "symbol",
      orderDir = "asc",
      meta = "field.shortName,field.type,field.description",
      hasOptions = TRUE,
      #page = 1,
      #limit = 100,
      raw = 1
    ),
    content_type_json(),
    accept_json(),
    add_headers(
      "x-xsrf-token" = xsrf_token,
      "referrer" = "https://www.barchart.com/options/stocks-by-sector?page=1"
    )
  )

table_data <- req %>%
  content() %>%
  .$data %>%
  map_dfr(unlist)

这将为您提供包含 4258 项的完整列表,并为方便起见将其强制转换为 tibble :)