Mam listę 40 000 adresów stron internetowych wplik csv. Chcę przeczytać te strony w nowym pliku CSV tak, aby każda komórka w pliku CSV była zawartością powiązanej strony internetowej. Jestem w stanie odczytywać (parsować) pojedynczą stronę za pomocą następującego kodu
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 = " ")
czy możliwe jest użycie csv z adresem strony internetowej jako danych wejściowych i pobranie nowego pliku z całą zawartością, o której mowa powyżej?
Odpowiedzi:
0 dla odpowiedzi № 1możesz spróbować następującego kodu. Powinno to zadziałać, jeśli chodzi o twoje cele, ale nie zostało przetestowane, ponieważ nie znam stron, na które warto spojrzeć:
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)
Jeśli chcemy tego samego czasu, możemy użyć doParallel
biblioteka w R, to skonfiguruje wiele klastrów (instancji R) i powinno przyspieszyć twój proces.
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)