跨多个页面的Web剪贴R

  • 本文关键字:Web 剪贴 r web-scraping
  • 更新时间 :
  • 英文 :


我一直在编写一些R代码。目的是收集一个有50个页面的网站的一个部分中单词的平均单词长度和其他统计数据。收集统计数据是没有问题的,这是一个简单的部分。然而,让我的代码收集50多页的统计数据是困难的部分,它似乎只从第一页输出信息。请参阅下面的代码,忽略不正确的缩进。

install.packages(c('tidytext', 'tidyverse'))
library(tidyverse)
library(tidytext)
library(rvest)
library(stringr)
websitePage <- read_html('http://books.toscrape.com/catalogue/page-1.html')
textSort <- websitePage %>%
html_nodes('.product_pod a') %>%
html_text()

for (page_result in seq(from = 1, to = 50, by = 1)) {
link = paste0('http://books.toscrape.com/catalogue/page-',page_result,'.html')
page = read_html(link)
# Creates a tibble
textSort.tbl <- tibble(text = textSort)
textSort.tidy <- textSort.tbl %>%
funnest_tokens(word, text)
}
# Finds the average word length
textSort.tidy %>%
map(nchar) %>%
map(mean)
# Finds the most common words
textSort.tidy %>%
count(word, sort = TRUE)
# Removes the stop words and then finds most common words
textSort.tidy %>%
anti_join(stop_words) %>%
count(word, sort = TRUE)
# Counts the number of times the word "Girl" is in the text
textSort.tidy %>%
count(word) %>%
filter(word == "Girl")

您可以使用lapply/map从多个链接中提取tetx。

library(rvest)
link <- paste0('http://books.toscrape.com/catalogue/page-',1:50,'.html')
result <- lapply(link, function(x) x %>% 
read_html %>% 
html_nodes('.product_pod a') %>%
html_text)

如果要将其他函数应用于文本,则可以继续使用lapply

最新更新