Eu tenho uma lista de 40.000 endereços de páginas da web em umarquivo csv. Eu quero ler essas páginas em um novo arquivo csv tal que cada célula no csv é o conteúdo da página da web associada. Eu sou capaz de ler (analisar) uma única página usando o seguinte código
library(XML)
# Read and parse HTML file
doc.html = htmlTreeParse("",useInternal = TRUE)
# Extract all the paragraphs (HTML tag is p, starting at
# the root of the document). Unlist flattens the list to
# create a character vector.
doc.text = unlist(xpathApply(doc.html, "//p", xmlValue))
# Replace all n by spaces
doc.text = gsub("\n", " ", doc.text)
# Join all the elements of the character vector into a single
# character string, separated by spaces
doc.text = paste(doc.text, collapse = " ")
é possível usar o csv tendo o endereço das páginas da web como entrada e obter um novo arquivo com todo o conteúdo mencionado acima?
Respostas:
0 para resposta № 1você poderia tentar o seguinte código. Deve funcionar os seus propósitos, mas o seu não testado como eu não sei os sites que você está querendo olhar:
library(XML)
library(rvest)
df <- read.csv("Webpage_urls.csv", stringsAsFactors = F)
webpage_parser <- function(x){
x <- read_html(x)
doc.html = htmlTreeParse(x, useInternal = TRUE)
# Extract all the paragraphs (HTML tag is p, starting at
# the root of the document). Unlist flattens the list to
# create a character vector.
doc.text = unlist(xpathApply(doc.html, "//p", xmlValue))
# Replace all n by spaces
doc.text = gsub("\n", " ", doc.text)
# Join all the elements of the character vector into a single
# character string, separated by spaces
doc.text = paste(doc.text, collapse = " ")
}
all_webpages <- lapply(df, function(x) webpage_parser(x))
Pages <- do.call(rbind, all_webpages)
Parsed_pages <- cbind(df, Pages)
write.csv(Parsed_pages, "All_parsed_pages.csv", row.names = F)
Se quisermos o mesmo tempo, podemos usar o doParallel
biblioteca em R, isso irá configurar vários clusters (instâncias de R) e deve ajudar a acelerar o seu processo.
library(doParallel)
# split your webpage list into n vectors and create a list called Split_df
Split_df <- list(df1, df2, df3,..., dfn)
# Here I initiate my cluster
cl <- makeCluster(detectCores()-1)
registerDoParallel(cl)
Parsed_pages <- foreach(i = 1:length(Split_df), .combine = rbind) %dopar%
{
library(rvest)
library(XML)
all_webpages <- lapply(Split_df[[i]], function(x) webpage_parser(x))
Pages <- do.call(rbind, all_webpages)
Parsed_pages <- cbind(Split_df[[i]], Pages)
Parsed_pages
}
stopCluster(cl)
write.csv(Parsed_pages, "All_parsed_pages.csv", row.names = F)