【发布时间】:2019-11-18 10:05:30
【问题描述】:
我正在尝试使用循环函数从网站上抓取一些文本,但我的循环函数不会继续选择矢量列表中的下一项。感谢任何有用的建议。谢谢
library(rvest)
library(xml2)
ID <- c(1:2)
Land <- c('Afghanistan','Ägypten')
url <- c('afghanistan', 'aegypten')
Text <- (NA)
data <- data.frame(ID, Land, Text)
for(i in url) {
nam <- paste("https://www.reporter-ohne-grenzen.de", i, sep = "/")
assign(nam, i)
webpage <- read_html(paste0(nam, i))
data$Text <- i <- webpage %>% html_nodes('div.text') %>% .[[1]] %>% html_text()
}
嗯,不知道我是否把我的问题说清楚了。这是我想要的数据输出的一个例子。
library(rvest)
library(xml2)
ID <- c(1:2)
Land <- c('Afghanistan','Ägypten')
url <- c('afghanistan', 'aegypten')
Text <- (NA)
data <- data.frame(ID, Land, Text)
afghanistan <- 'https://www.reporter-ohne-grenzen.de/afghanistan'
afghanistan <- read_html(afghanistan)
afghanistan <- html_nodes(afghanistan,'div.text')
afghanistan <- html_text(afghanistan)[[1]]
aegypten <- 'https://www.reporter-ohne-grenzen.de/aegypten'
aegypten <- read_html(aegypten)
aegypten <- html_nodes(aegypten,'div.text')
aegypten <- html_text(aegypten)[[1]]
# desired data output
data$Text <- c(afghanistan, aegypten)
我不想在 180 个国家/地区重复这些行。
aegypten <- 'https://www.reporter-ohne-grenzen.de/aegypten'
aegypten <- read_html(aegypten)
aegypten <- html_nodes(aegypten,'div.text')
aegypten <- html_text(aegypten)[[1]]
解决方案如下:
library(rvest)
library(xml2)
ID <- c(1:4)
Land <- c('Afghanistan','Ägypten','Deutschland','Italien')
Url <- c('afghanistan', 'aegypten','deutschland','italien')
Text <- NA
data <- data.frame(ID, Land, Text)
website <- 'https://www.reporter-ohne-grenzen.de'
for (i in ID) {
country <- Url[i]
html_url <- paste(website,country,sep='/')
output <- read_html(html_url)
output <- html_nodes(output,'div.text')
output <- html_text(output)[[1]]
data$Text[i] <- output
}
【问题讨论】:
-
你为什么使用
assign?变量nam应该足够用在read_html中了,为什么还要加上i。我建议使用sapply或lapply,因为这样您就可以在列表中获得结果,然后可以将其取消列出并从中创建一个data.frame。
标签: r loops web-scraping rvest xml2