2016-03-31 32 views
2

我試圖抓住一個數據表使用從R包rvest read_html。web刮與rvest

我嘗試下面的代碼:

library(rvest) 
    raw <- read_html("https://demanda.ree.es/movil/peninsula/demanda/tablas/2016-01-02/2") 

我不相信從上面的表格拉的數據,因爲我看到的「原始」是2的列表:

'node:<externalptr>' and 'doc:<externalptr>' 

我試圖抓住的XPath太:什麼嘗試下一個

html_nodes(raw,xpath = '//*[(@id = "tabla_generacion")]//*[contains(concat(" ", @class, " "), concat(" ", "ng-scope", " "))]') 

有什麼建議?

謝謝。

回答

4

本網站使用angular來撥打電話以獲取數據。您可以使用該調用來獲取原始JSON。響應不是純粹的JSON,所以你不能只運行fromJSON(url),你必須下載數據並在解析之前擺脫非JSON的東西。

library(jsonlite) 
library(httr) 
url <- "https://demanda.ree.es/WSvisionaMovilesPeninsulaRest/resources/demandaGeneracionPeninsula?callback=angular.callbacks._2&curva=DEMANDA&fecha=2016-01-02" 
a <- GET(url) 
a <- content(a, as="text") 
# get rid of the non-JSON stuff... 
a <- gsub("^angular.callbacks._2\\(", "", a) 
a <- gsub("\\);$", "", a) 
df <- fromJSON(a, simplifyDataFrame = TRUE) 

我通過在Chrome中按F12並查看「Sources」選項卡找到了這個。填滿表格的數據必須來自某個地方...所以這只是一個確定問題的地方。我無法使用rvest來刮桌子。我不確定是否在R中執行了獲取數據的調用,因爲它是在chrome中的......所以可能沒有任何數據可供刮取。

enter image description here

+0

太棒了,謝謝!你有什麼機會可以解釋你在哪裏找到這個電話?可以通過在Chrome中使用「檢查」來找到它嗎? – cam333

+0

@ cam333我更新了我的答案更詳細 – cory

+0

非常酷,感謝您的解釋。這對我來說會派上用場。 – cam333