首页 > 解决方案 > 逐页从网页中提取表格

问题描述

我已经为网页中的网页抓取表编写了代码。此代码从第一页中提取表格(在 url /page=0 中):

url <- "https://ss0.corp.com/auth/page=0"
login <- "john.johnson" (fake)
password <- "67HJL54GR" (fake)

res <- GET(url, authenticate(login, password))
content <- content(res, "text")

table <- fromJSON(content) %>%
  as.data.farme()

我想编写一个代码来逐页从表中提取行,然后绑定它们。我这样做,因为表太大,我不能一次提取所有东西(它会破坏系统)。我不知道可以有多少页,它会发生变化,因此一旦收集到最后一页,它就必须停止。我怎么能这样做?

标签: rfunctionwebweb-scrapinghttr

解决方案


我无法测试以保证这会起作用,因为该问题不可重现,但您主要需要三个步骤:

  1. 设置 url 和凭据

    url <- "http://someurl/auth/page="
    login <- ""
    password <- ""
    
  2. 遍历所有(我假设有N)页面并将结果存储在列表中。请注意,我们为每个页面正确修改了 url。

    tables <- lapply(1:N, function(page) {
      # Create the proper url and make the request
      this_url <- paste0(url, page)
      res <- GET(this_url, authenticate(login, password))
    
      # Extract the content just like you would in a single page
      content <- content(res, "text")
      table <- fromJSON(content) %>%
        as.data.frame()
      return(table)}
    )
    
  3. 使用将列表中的所有表聚合到一个完整的表中rbind

    complete <- do.call(rbind, tables)
    

我希望这至少有助于指明方向。


推荐阅读