【问题标题】:Web Scraping Across multiple pages R跨多个页面的网页抓取 R
【发布时间】:2021-09-30 04:45:52
【问题描述】:

我一直在编写一些 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")

【问题讨论】:

  • 只输出第一个还是最后一个?

标签: r web-scraping


【解决方案1】:

我有两点要说。首先,您在代码中使用了 funnest_tokens 函数,该函数不存在。你是说 unnest_tokens 吗?

其次,您可以尝试使用 purrr 包中的 map* 函数来代替循环。首先,创建一个返回 tibble 的函数。它应该包含您需要的统计信息 - 例如最常用的词。并创建一个您要从中抓取数据的网页列表。然后使用地图功能。应该可以吧。

【讨论】:

    【解决方案2】:

    您可以使用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

    【讨论】:

      猜你喜欢
      • 2016-08-09
      • 2019-02-16
      • 2022-01-21
      • 1970-01-01
      • 2017-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多