【发布时间】:2021-09-10 13:35:38
【问题描述】:
说明:尝试使用 httr 库从 Investing.com 检索历史数据
原始页面:https://www.investing.com/rates-bonds/austria-1-year-bond-yield-historical-data
预期输出:带有历史数据的 html 表格:sample table output
脚本逻辑:
- 使用
httr发送POST查询 - 使用
html_table方法美化read_html方法的输出
问题:
- 脚本从主页而不是实际的历史表中检索表
代码:
library(httr)
url <- 'https://www.investing.com/instruments/HistoricalDataAjax'
# mimic XHR POST request implemented in the investing.com website
http_resp <- POST(url = url,
body = list(
curr_id = "23859",
smlID = "202274",
header = "Austria+1-Year+Bond+Yield+Historical+Data",
st_date = "08/01/2021", # MM/DD/YYYY format
end_date = "08/20/2021",
interval_sec = "Daily",
sort_col = "date",
sort_ord = "DESC",
action = "historical_data"
)
)
# parse the returned XML
html_doc <- read_html(http_resp)
print(html_table(html_doc)[[1]])
您可能会注意到,与原始网页 https://www.investing.com/rates-bonds/austria-1-year-bond-yield-historical-data 相比,R 脚本中使用的 URL 使用了不同的 URL https://www.investing.com/instruments/HistoricalDataAjax。其原因显然是设置开始日期和结束日期时 POST 请求中使用的链接。您可能会在下面的屏幕截图中看到这一点:
XHR request header when setting the start and end dates
据我所知,当用户指定特定证券的日期时,网站会向HistoricalDataAjax 发送查询,并在请求正文中指定证券/资产的参数和标识符:Example of the requests's body after selecting dates
【问题讨论】:
-
链接
https://www.investing.com/instruments/HistoricalDataAjax正在返回首页。你能提供一个正确的链接吗? -
嗨@NadPat!很高兴看到这篇文章引起了你的注意。这是原始链接:investing.com/rates-bonds/… 不过考虑一下,我使用了 HistoricaDataAjax,因为这就是原始 Header 请求似乎是 POST 查询的方式。我将在原始帖子中添加更多说明以使其清楚。
-
要下载您需要登录的数据。
RSelenium解决方案是否适合您? -
我不想使用 Selenium。首先,因为它引入了对用户机器的额外依赖。其次,我希望执行速度会慢一些。第三,我知道使用 POST 请求可以绕过登录过程:当通过 XHR 在 Web 上更新数据时,可以获取 HTML 表。真正的问题是正确获取它。我知道
investpy的实现方式完全一样。investpy虽然是一个 Python 库,但我需要在 R 中实现。
标签: jquery r post httr web-mining