web-scraping - Rvest 不会返回数据
问题描述
我一直在尝试抓取下表:
解决方案
您的问题是您的请求为您提供了一个 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 :)
推荐阅读
- r - 无法为条形图安排中断和标签
- sql - 用户分配订单
- ios - 将项目从 xcode 8 迁移到 xcode 9 在启动器屏幕上崩溃
- redis - 该组中的任何人都在将 Redis 作为数据库工作
- python - 如何在 weka 包装器中使用 pandas datafames 而不是 arff 文件?
- c# - 保存从数据库检索到的图像时出错
- scrapy - 使scrapy蜘蛛跟随给定起始网址中的链接
- amazon-web-services - 在 emr 5.16 上将 jupyterhub notebook_dir 设置为 s3
- android - 没有 BrowseFragment 的 Leanback 库中的 RowFragment
- java - 从网站获取 android 实时比分应用程序的数据