2017-03-17 37 views
0

當試圖解析一個html頁面時,我們可以得到NA值。因此,當我們嘗試使用列表中的數據構建數據框時,缺少值將無法實現。如何在解析html頁面來替換數據框時替換NA值?

有什麼簡單的方法可以成功。請看下面的例子:

library(rvest) 
library(RCurl) 
library(XML) 

pg <- getURL("https://agences.axa.fr/ile-de-france/paris/paris-19e-75019") 
page = htmlTreeParse(pg,useInternal = TRUE,encoding="UTF-8") 
unlist(xpathApply(page,'//b[@class="Name"]',xmlValue)) 
data.frame(noms = unlist(xpathApply(page,'//b[@class="Name"]',xmlValue)), 
      rue = unlist(xpathApply(page,'//span[@class="street-address"]',xmlValue))) 
+0

因爲您使用'html_node'而不是'html_nodes'。此外,RCurl在這裏是不必要的;你可以直接將URL傳遞給'read_html'。 – alistaire

+0

謝謝@alistaire,我修改了我的問題,因爲最初的一個很愚蠢。對於這個問題,我已經問過類似的問題:http://stackoverflow.com/questions/42588717/how-to-return-na-when-nothing-is-found-in-an-xpath,根據您對其他問題的回答,您可以成功找到解決方案。 –

+0

更好的問題。但是,您應該顯示加載XML,以獲得可重複性。 – alistaire

回答

0

使用rvest和purrr(的tidyverse包列表/功能編程,這對非常很好地與rvest)

library(rvest) 
library(purrr) 

# be nice, only scrape once 
h <- 'https://agences.axa.fr/ile-de-france/paris/paris-19e-75019' %>% read_html() 

df <- h %>% 
    # select each list item 
    html_nodes('div.ListConseiller li') %>% 
    # for each item, make a list of parsed name and street; coerce results to data.frame 
    map_df(~list(nom = .x %>% html_node('b.Name') %>% html_text(), 
       rue = .x %>% html_node('span.street-address') %>% html_text(trim = TRUE))) 

df 
#> # A tibble: 14 × 2 
#>       nom      rue 
#>      <chr>     <chr> 
#> 1   Marie France Tmim     <NA> 
#> 2    Rachel Tobie     <NA> 
#> 3    Bernard Licha     <NA> 
#> 4    David Giuili     <NA> 
#> 5  Myriam Yajid Khalfi     <NA> 
#> 6    Eytan Elmaleh     <NA> 
#> 7   Allister Charles     <NA> 
#> 8    Serge Savergne 321 Rue De Belleville 
#> 9   Patrick Allouche   1 Rue Clavel 
#> 10    Anne Fleiter 14 Avenue De Laumiere 
#> 11    Eric Fitoussi     <NA> 
#> 12 Jean-Baptiste Crocombette 1 Bis Rue Emile Desvaux 
#> 13    Eric Zunino 14 Rue De Thionville 
#> 14    Eric Hayoun     <NA> 

代碼使用CSS選擇爲但如果您願意,可以通過參數html_nodeshtml_nodexpath參數使用XPath參數。

+0

謝謝@alistaire,現在我開始明白了,順便說一下,我們也可以使用xpath:'xpath ='// div [@ class =「ListConseiller」] // li'' :) –

+0

也許我可以刪除這個問題,它在這裏是一樣的:http://stackoverflow.com/questions/42588717/how-to-return-na-when-nothing-is-found-in-an-xpath –

+0

你能告訴我爲什麼這不起作用? 'df <- h %>% html_nodes('div.ListConseiller li')%>% map_df(〜list(nom = .x%>%html_nodes(xpath ='// b [@ class =「Name」]')%> %html_text(), rue = .x%>%html_nodes(xpath ='// span [@ class =「street-address」]')%>%html_text(trim = TRUE)))'或者我怎麼找到與'xpath'等價的方式? –