我想使用http://finra-markets.morningstar.com/BondCenter/TRACEMarketAggregateStats.jsp的rvest(任何日期)提取下表:
我尝试了以下但未能产生任何结果:
library(rvest)
url <- "http://finra-markets.morningstar.com/BondCenter/TRACEMarketAggregateStats.jsp"
htmlSession <-html_session(url) ## create session
goForm <- html_form(htmlSession)[[2]] ## pull form from session
#filledGoForm <- set_values(goForm, value="04/26/2017") # This does not work
filledGoForm <- goForm
filledGoForm$fields[[1]]$value <- "04/26/2017"
htmlSession <- submit_form(htmlSession, filledGoForm)
> htmlSession <- submit_form(htmlSession, filledGoForm)
Submitting with ''
Warning message:
In request_POST(session, url = url, body = request$values, encode = request$encode, :
Not Found (HTTP 404).
有关如何做到这一点的任何提示都受到高度赞赏。
答案 0 :(得分:2)
该网站使用许多XHR请求来填充表格。并且,它建立了一个带有隐藏POST
请求的服务器会话,该请求不会被html_session()
复制。
我们需要在httr
中添加一些帮助:
library(httr)
library(rvest)
我们需要做的第一件事就是点击网站,将初始qs_wid
Cookie放入隐式Cookie jar curl
/ httr
/ rvest
分享中:
init <- GET("http://finra-markets.morningstar.com/MarketData/Default.jsp")
接下来,我们需要模仿隐藏的&#34;登录&#34;网页的确如此:
nxt <- POST(url = "http://finra-markets.morningstar.com/finralogin.jsp",
body = list(redirectPage = "/BondCenter/TRACEMarketAggregateStats.jsp"),
encode = "form")
这会在服务器后端创建一个会话,并在我们的cookie jar中放置一些其他cookie。
最后:
GET(
url = "http://finra-markets.morningstar.com/transferPage.jsp",
query = list(
`path`="http://muni-internal.morningstar.com/public/MarketBreadth/C",
`date`="04/24/2017",
`_`=as.numeric(Sys.time())
)
) -> res
发出请求。您可以从所有三个步骤(一起)中创建一个函数,并参数化最后GET
。
不幸的是,这会返回一个非常破碎的HTML <table>
,html_table()
无法自动为您转换为数据框,但这不应该阻止您:
content(res) %>%
html_nodes("td") %>%
html_text() %>%
matrix(ncol=4, byrow=TRUE) %>%
as_data_frame() %>%
mutate_all(as.numeric) %>%
rename(all_issues=V1, investment_grade=V2, high_yield=V3, convertible=V4) %>%
mutate(category = c("total_issues_traded", "advances", "declines", "unchanged", "high_52", "low_52", "dollar_volume"))
## # A tibble: 7 × 5
## all_issues investment_grade high_yield convertible category
## <dbl> <dbl> <dbl> <dbl> <chr>
## 1 7983 5602 2194 187 total_issues_traded
## 2 3025 1798 1100 127 advances
## 3 4448 3575 824 49 declines
## 4 124 42 75 7 unchanged
## 5 257 66 175 16 high_52
## 6 139 105 33 1 low_52
## 7 22601 16143 5742 715 dollar_volume
要获取其他数据表,请转到浏览器中的“开发人员工具”选项(如果您没有,那么请切换到拥有该数据表的选项...鉴于您正在进行操作,您很可能在Windows上财务事项和IE / Edge不是非常好的内省浏览器)并刷新页面以查看其他请求。