2016-06-23 4 views
1

오바마의 스펙 페이지를 워드 스크랩 등으로 만들기 위해 시도합니다. 1, 5, 10 개의 다른 페이지 (연설) , 루프 안에, 분리되어, 부호는 작동한다. 그러나 위의 루프를 만들면 결과 개체에 아무 것도 포함되지 않습니다 (NULL).r (루프 포함)에서 웹 스크 레이 핑

누군가 나를 도울 수 있습니까? CSS 또는 XPath를 선택기의 지식이 조금 필요가있을 수 있지만

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 '을 +와'에 루프를 변경하기위한 (전 1 : nrow (teste5))' – HubertL

답변

1

rvest 패키지는, 스크래핑 및 파싱하여이 상당히 간단합니다. HTML에서 regex를 사용하는 것보다 훨씬 좋은 접근 방법입니다. 적절한 HTML 구문 분석기 (예 : rvest!)를 사용하는 것이 좋습니다.

여러 페이지의 하위 페이지를 다듬 으려는 경우 URL 벡터를 만들고 그 다음에 lapply을 붙여 각 페이지를 긁어 분석 할 수 있습니다. 이 방법의 장점은 (for 루프 이상) 각 반복마다 항목이있는 목록을 반환한다는 것입니다 (which will be much easier to deal with afterwards). 해들리 부두 (Hadleyverse)를 풀고 싶다면 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로 키워드를 검색하고 찾은 키워드를 다시 가져 오십시오. –

관련 문제