2015-06-20 93 views
3

我正在試驗rvest學習網絡抓取R.我試圖複製樂高榜樣的頁面的其他幾節,並使用selector gadget id。網站抓取與R和rvest

我從R Studio tutorial拉下了這個例子。用下面的代碼,1和2工作,但3不工作。

library(rvest) 
lego_movie <- html("http://www.imdb.com/title/tt1490017/") 

# 1 - Get rating 
lego_movie %>% 
    html_node("strong span") %>% 
    html_text() %>% 
    as.numeric() 

# 2 - Grab actor names 
lego_movie %>% 
    html_nodes("#titleCast .itemprop span") %>% 
    html_text() 

# 3 - Get Meta Score 
lego_movie %>% 
    html_node(".star-box-details a:nth-child(4)") %>% 
    html_text() %>% 
    as.numeric() 

回答

3

我真的不加快速度上的所有管道和相關的代碼,因此可能有一些新的fandangled工具來做到這一點......但鑑於上面的回答讓你到"83/100",你可以做這樣的事情:

as.numeric(unlist(strsplit("83/100", "/")))[1] 
[1] 83 

我猜會是這個樣子與管道:

lego_movie %>% 
    html_node(".star-box-details a:nth-child(4)") %>% 
    html_text(trim=TRUE) %>% 
    strsplit(., "/") %>% 
    unlist(.) %>% 
    as.numeric(.) %>% 
    head(., 1) 

[1] 83 

或者像弗蘭克說,你可以計算表達式"83/100"類似於:

lego_movie %>% 
    html_node(".star-box-details a:nth-child(4)") %>% 
    html_text(trim=TRUE) %>% 
    parse(text = .) %>% 
    eval(.) 
[1] 0.83 
2

你可以看到,轉換成數字之前,它返回一個" 83/100\n"

lego_movie %>% 
    html_node(".star-box-details a:nth-child(4)") %>% 
    html_text() 
# [1] " 83/100\n" 

您可以使用trim=TRUE省略\n。您無法將其轉換爲數字,因爲您有/。 :

lego_movie %>% 
    html_node(".star-box-details a:nth-child(4)") %>% 
    html_text(trim=TRUE) 
# [1] "83/100" 

如果你將它轉換爲數字,你會得到NA有警告這並不意外:

# [1] NA 
# Warning message: 
# In function_list[[k]](value) : NAs introduced by coercion 

如果你想在數字83作爲最終的答案,你可以使用正則表達式工具如gsub刪除100\(假設所有電影的滿分爲100)。

lego_movie %>% 
    html_node(".star-box-details a:nth-child(4)") %>% 
    html_text(trim=TRUE) %>% 
    gsub("100|\\/","",.)%>% 
    as.numeric() 
# [1] 83