0

描述:尝试使用httr库从 Investing.com 检索历史数据

原始页面https ://www.investing.com/rates-bonds/austria-1-year-bond-yield-historical-data

预期输出:带有历史数据的 html 表:示例表输出

脚本逻辑

  • 发送POST查询httr
  • read_htmlhtml_table方法美化方法的输出

问题

  • 脚本从主页而不是实际的历史表中检索表

代码

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

您可能会注意到 R 脚本中使用的 URLhttps://www.investing.com/instruments/HistoricalDataAjax与原始 web-page 相比使用了不同的 URL https://www.investing.com/rates-bonds/austria-1-year-bond-yield-historical-data。其原因显然是设置开始日期和结束日期时 POST 请求中使用的链接。您可能会在下面的屏幕截图中看到这一点:

设置开始和结束日期时的 XHR 请求标头

据我所知,当用户指定特定证券的日期时,网站会向HistoricalDataAjax请求正文中指定的证券/资产的参数和标识符发送查询:选择日期后请求正文的示例

4

1 回答 1

0

你可以把桌子放进去,

https://www.investing.com/rates-bonds/austria-1-year-bond-yield-historical-data

使用rvest

library(rvest)
df = url %>%
  read_html() %>% 
  html_table()

df[[1]]
# A tibble: 25 x 6
   Date          Price   Open   High    Low `Change %`
   <chr>         <dbl>  <dbl>  <dbl>  <dbl> <chr>     
 1 Dec 09, 2021 -0.669 -0.672 -0.633 -0.695 11.69%    
 2 Dec 08, 2021 -0.599 -0.6   -0.549 -0.647 -2.28%    
 3 Dec 07, 2021 -0.613 -0.621 -0.536 -0.656 -7.54%    
 4 Dec 06, 2021 -0.663 -0.648 -0.565 -0.687 -0.30%    
 5 Dec 03, 2021 -0.665 -0.681 -0.577 -0.684 0.45%     
 6 Dec 02, 2021 -0.662 -0.59  -0.573 -0.669 0.46%     
 7 Dec 01, 2021 -0.659 -0.608 -0.577 -0.685 1.70%     
 8 Nov 30, 2021 -0.648 -0.697 -0.601 -0.736 -4.85%    
 9 Nov 29, 2021 -0.681 -0.715 -0.647 -0.745 -12.47%   
10 Nov 27, 2021 -0.778 -0.701 -0.701 -0.778 7.61%  
于 2021-12-09T13:27:20.333 回答