我颳了以下網站:https://www.banorte.com/wps/portal/ixe/Home/indicadores/tipo-de-cambio刮JavaScript對象和R /內轉換成JSON Rvest
我試圖讓貨幣匯率表到通過rvest包R的數據框,但表格本身是在HTML代碼中的JavaScript變量中配置的。
我所在的相關CSS選擇器,現在我有這個:
library(rvest)
banorte <- "https://www.banorte.com/wps/portal/ixe/Home/indicadores/tipo-de-cambio/" %>%
read_html() %>%
html_nodes('#indicadores_financieros_wrapper > script:nth-child(2)')
我的輸出是現在下面的JavaScript腳本,作爲XML節點集:
<script>
$(document).ready(function(){
var valor = '{"tablaDivisas":[{"nombreDivisas":"FRANCO SUIZO","compra":"18.60","venta":"19.45"}, {"nombreDivisas":"LIBRA ESTERLINA","compra":"24.20","venta":"25.15"}, {"nombreDivisas":"YEN JAPONES","compra":"0.1635","venta":"0.171"}, {"nombreDivisas":"CORONA SUECA","compra":"2.15","venta":"2.45"}, {"nombreDivisas":"DOLAR CANADA","compra":"14.50","venta":"15.35"}, {"nombreDivisas":"EURO","compra":"21.75","venta":"22.60"}], "tablaDolar":[{"nombreDolar":"VENTANILLA","compra":"17.73","venta":"19.15"}]}';
if(valor != '{}'){
var objJSON = eval("(" + valor + ")");
var tabla="<tbody>";
for (var i = 0; i < objJSON["tablaDolar"].length; i++) {
tabla+= "<tr>";
tabla+= "<td>" + objJSON["tablaDolar"][i].nombreDolar + "</td>";
tabla+= "<td>$" + objJSON["tablaDolar"][i].compra + "</td>";
tabla+= "<td>$" + objJSON["tablaDolar"][i].venta + "</td>";
tabla+= "</tr>";
}
tabla+= "</tbody>";
$("#tablaDolar").append(tabla);
var tabla2="";
for (var i = 0; i < objJSON["tablaDivisas"].length; i++) {
tabla2+= "<tr>";
tabla2+= "<td>" + objJSON["tablaDivisas"][i].nombreDivisas + "</td>";
tabla2+= "<td>$" + objJSON["tablaDivisas"][i].compra + "</td>";
tabla2+= "<td>$" + objJSON["tablaDivisas"][i].venta + "</td>";
tabla2+= "</tr>";
}
tabla2+= "</tbody>";
$("#tablaDivisas").append(tabla2);
}
bmnIndicadoresResponsivoInstance.cloneResponsive(0);
});
</script>
我的問題是,怎麼辦我刪除了幾乎所有的JavaScript函數/操作符,以僅獲取此數據,並將其最終轉換爲JSON表,如下所示:
{"tablaDivisas":[{"nombreDivisas":"FRANCO SUIZO","compra":"18.60","venta":"19.45"},
{"nombreDivisas":"LIBRA ESTERLINA","compra":"24.20","venta":"25.15"},
{"nombreDivisas":"YEN JAPONES","compra":"0.1635","venta":"0.171"},
{"nombreDivisas":"CORONA SUECA","compra":"2.15","venta":"2.45"},
{"nombreDivisas":"DOLAR CANADA","compra":"14.50","venta":"15.35"},
{"nombreDivisas":"EURO","compra":"21.75","venta":"22.60"}],
"tablaDolar":[{"nombreDolar":"VENTANILLA","compra":"17.73","venta":"19.15"}]}
換句話說,我需要從使用R.
出於某種原因,我有麻煩完成這件事都在R(JS腳本提取「英勇」的變量,而不必變量導出爲外部.txt文件,然後使用一個子)