【问题标题】:Rvest wont return dataRvest 不会返回数据
【发布时间】:2020-08-08 08:39:17
【问题描述】:

我一直在尝试抓取下表:

【问题讨论】:

    标签: web-scraping rvest httr jsonlite


    【解决方案1】:

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

    无论哪种方式,在您链接的表后面对 API 请求的基本要素进行逆向工程,您都必须将这样的东西放在一起:

    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 :)

    【讨论】:

      猜你喜欢
      • 2019-02-13
      • 2018-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-03
      • 1970-01-01
      相关资源
      最近更新 更多