2015-05-30 46 views
0

我想獲得與任何給定的郵政編碼相關的洪水風險,並且希望使用this website來完成此操作。然後點擊純文字。R解析HTML以獲得值

我想給它一個郵政編碼和得到一個TRUE或FALSE響應查詢這個網站的基礎上,如果響應回來爲是或否。

下面是迄今爲止我所編寫的代碼嘗試和產生這個...

但我htmlresp_content對象有一類"HTMLInternalDocument" "HTMLInternalDocument" "XMLInternalDocument" "XMLAbstractDocument",我不知道如何解析/提取相關信息....

postcode_flood_risk <- function(PC){ 

    require(httr) 

    htmlresp <- GET(paste0('http://maps.environment-agency.gov.uk/wiyby/wiybyController?value=', 
          gsub(' ','+',PC), 
          '&submit.x=-1&submit.y=11&submit=Search%09&lang=_e&ep=summary&topic=floodmap&layerGroups=default&scale=9&textonly=off')) 

    htmlresp_content <- content(htmlresp) 

    # code to extract the 'Yes' or 'No' from htmlresp_content 
    # for now automatically choose yes 
    flood_risk <- 'Yes' 

    if(flood_risk=='Yes'){ 
     TRUE 
    } else { 
     FALSE 
    } 
    } 
+0

你能給我們一個工作的網址嗎?我需要一個「個人電腦」,用你的GET語句來看看發生了什麼...... – cory

回答

1

您可以添加一些xpath得到響應

postcode_flood_risk <- function(PC){ 
    require(httr) 
    htmlresp <- GET(paste0('http://maps.environment-agency.gov.uk/wiyby/wiybyController?value=', 
          gsub(' ','+',PC), 
          '&submit.x=-1&submit.y=11&submit=Search%09&lang=_e&ep=summary&topic=floodmap&layerGroups=default&scale=9&textonly=off')) 

    htmlresp_content <- content(htmlresp) 

    # extract the 'Yes' 
    out <- htmlresp_content["//table[2]//td[2]//text()"] 
    flood_risk <- gsub("\\t|\\r|\\n", "", xmlValue(out[[1]])) 

    if(!is.na(flood_risk) && flood_risk=='Yes'){ 
     TRUE 
    } else { 
     FALSE 
    } 
} 

postcode_flood_risk("FY6 0AA") 
# TRUE 
postcode_flood_risk("FY6 0A9") 
# FALSE 
+0

本着教導一個人如何去釣魚......給他一條魚......你能告訴我你是如何知道的添加你添加的兩行...即'out < - htmlresp_content [「// table [2] // td [2] // text()」]; flood_risk < - gsub(「\\ t | \\ r | \\ n」,「」,xmlValue(out [[1]]))' –

+0

對不起,如果我慢了, HTML響應並查看我可以使用的標籤'? –