Ich habe eine Liste von 40.000 Webseiten-Adressen in einerCSV-Datei. Ich möchte diese Seiten in einer neuen CSV-Datei lesen, sodass jede Zelle in der CSV den Inhalt der zugehörigen Webseite darstellt. Ich kann eine einzelne Webseite mit folgendem Code lesen (analysieren)
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 = " ")
Ist es möglich, die csv mit der Adresse der Webseite als Eingabe zu verwenden und eine neue Datei mit dem gesamten Inhalt wie oben erwähnt zu erhalten?
Antworten:
0 für die Antwort № 1Sie könnten den folgenden Code ausprobieren. Es sollte funktionieren Ihre Ziele, aber es ist ungeprüft, da ich nicht weiß, welche Websites Sie anzeigen möchten:
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)
Wenn wir gleichzeitig wollen, können wir die verwenden doParallel
Wenn Sie eine Bibliothek in R einrichten, werden mehrere Cluster (Instanzen von R) eingerichtet und sollten Ihren Prozess beschleunigen.
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)