2016-06-23 10 views
1

オバマのスペシャルページをウェブスクラップして、ワードクラウドなどを作成しようとしています。 1、5、10の異なるページ(スピーチ) 、ループではなく、分離して、コードが動作します。しかし、私が作成したこのループでは、結果のオブジェクトには何も含まれていません(NULL)。r(ループ付き)のウェブスクレイピング

誰かが私を助けることができますか?

library(wordcloud) 
library(tm) 
library(XML) 
library(RCurl) 

site <- "http://obamaspeeches.com/" 
url <- readLines(site) 

h <- htmlTreeParse(file = url, asText = TRUE, useInternalNodes = TRUE, 
    encoding = "utf-8") 

# getting the phrases that will form the web adresses for the speeches 
teste <- data.frame(h[42:269, ]) 
teste2 <- teste[grep("href=", teste$h.42.269...), ] 
teste2 <- as.data.frame(teste2) 
teste3 <- gsub("^.*href=", "", teste2[, "teste2"]) 
teste3 <- as.data.frame(teste3) 
teste4 <- gsub("^/", "", teste3[, "teste3"]) 
teste4 <- as.data.frame(teste4) 
teste5 <- gsub(">.*$", "", teste4[, "teste4"]) 
teste5 <- as.data.frame(teste5) 

# loop to read pages 

l <- vector(mode = "list", length = nrow(teste5)) 
i <- 1 
for (i in nrow(teste5)) { 
    site <- paste("http://obamaspeeches.com/", teste5[i, ], sep = "") 
    url <- readLines(site) 
    l[[i]] <- url 
    i <- i + 1 
} 

str(l) 
+1

私は< '削除 - 1 'と'私は< - I + 1 'と'のためにあなたのループを変更する:私はsimliarプロセスをやってみたかった場合(I 1でnrow(teste5))' – HubertL

答えて

1

CSSやXPathのセレクタの知識のビットを必要とすることができるがrvestパッケージは、掻き取りおよび解析することによって、これはかなり簡単になります。 HTML上のregexを使うよりはるかに優れたアプローチです。これは適切なHTMLパーサー(例えばrvest!のようなもの)に賛成しません。

サブページの束を削り取る場合は、URLのベクトルを作成してからlapplyを作成し、各ページをスクラップして解析することができます。 (forループ以上の)このアプローチの利点は、反復ごとに項目を含むリストを返すことです。which will be much easier to deal with afterwards。フルハドレーverseに行きたい場合は、代わりにpurrr::mapを使うことができます。これにより、すべてを1つの大きな連続チェーンにすることができます。

library(rvest) 

baseurl <- 'http://obamaspeeches.com/' 

     # For this website, get the HTML, 
links <- baseurl %>% read_html() %>% 
    # select <a> nodes that are children of <table> nodes that are aligned left, 
    html_nodes(xpath = '//table[@align="left"]//a') %>% 
    # and get the href (link) attribute of that node. 
    html_attr('href') 

      # Loop across the links vector, applying a function that 
speeches <- lapply(links, function(url){ 
    # pastes the ULR to the base URL, 
    paste0(baseurl, url) %>% 
    # fetches the HTML for that page, 
    read_html() %>% 
    # selects <table> nodes with a width of 610, 
    html_nodes(xpath = '//table[@width="610"]') %>% 
    # get the text, trimming whitespace on the ends, 
    html_text(trim = TRUE) %>% 
    # and break the text back into lines, trimming excess whitespace for each. 
    textConnection() %>% readLines() %>% trimws() 
}) 
+0

が、複数のURLのキーワードを探していて、キーワードを取り戻そうとしていましたが、regexを使用する関数でlapplyを実行する方が速くなるか、特定の単語を解析する際に効率的なものがありますか?私は、50または100のURLを処理するのに本当に時間がかかる問題にぶつかっています。 –

+0

URLまたはそれが導くページを解析しようとしていますか?前者の場合は別の質問ですが、 'httr :: parse_url'などをチェックしてください。 – alistaire

+0

私はそれが導くページを解析し、そのページのすべてのHTMLを取り戻そうとしています。または、少なくともそのページのHTMLを検索してキーワードを取り戻します。 –