Очистите несколько URL с помощью rvest - PullRequest
1 голос
/ 25 февраля 2020

Как я могу очистить несколько URL при использовании read_html в rvest? Цель состоит в том, чтобы получить один документ, состоящий из текстовых тел из соответствующих URL-адресов, по которым можно выполнять различные анализы.

Я попытался объединить URL-адреса:

 url <- c("https://www.vox.com/","https://www.cnn.com/")
   page <-read_html(url)
   page
   story <- page %>%
        html_nodes("p") %>%  
        html_text

После read_html получить ошибку:

 Error in doc_parse_file(con, encoding = encoding, as_html = as_html, options = options) : 
 Expecting a single string value: [type=character; extent=3].

Не удивлен, поскольку read_html, вероятно, обрабатывает только один путь за раз. Однако можно ли использовать другую функцию или преобразование, чтобы можно было одновременно очистить несколько страниц?

1 Ответ

1 голос
/ 25 февраля 2020

Вы можете использовать map (или в базе R: lapply) для l oop через каждый url элемент; Вот пример

url <- c("https://www.vox.com/", "https://www.bbc.com/")
page <-map(url, ~read_html(.x) %>% html_nodes("p") %>% html_text())
str(page)
#List of 2
# $ : chr [1:22] "But he was acquitted on the two most serious charges he faced." "Health experts say it’s time to prepare for worldwide spread on all continents." "Wall Street is waking up to the threat of coronavirus as fears about the disease and its potential global econo"| __truncated__ "Johnson, who died Monday at age 101, did groundbreaking work in helping return astronauts safely to Earth." ...
# $ : chr [1:19] "" "\n                                                            The ex-movie mogul is handcuffed and led from cou"| __truncated__ "" "27°C" ...

Возвращаемым объектом является list.

PS. Я изменил второй url элемент, потому что "https://www.cnn.com/" вернул NULL для html_nodes("p") %>% html_text().

...