【问题标题】:Scraping data from a site with multiple urls从具有多个 url 的站点中抓取数据
【发布时间】:2016-12-17 08:01:09
【问题描述】:

我一直在尝试从网站 -Company list401.html 上抓取公司列表。我可以使用以下代码从该页面上刮下单个表格:

>fileurl = read_html("http://archive.fortune.com
/magazines/fortune/fortune500_archive/full/2005/1")
> content = fileurl %>%
+ html_nodes(xpath = '//*[@id="MagListDataTable"]/table[2]') %>%
+ html_table()
>contentframe = data.frame(content)
> view(contentframe)

但是,我需要从 2005 年回溯到 1955 年的所有数据以及从 1 到 500 家公司的列表,而该列表一次只显示 100 家公司和一年。我已经认识到对 url 的唯一更改是 "...fortune500_archive/full/" YEAR "/" 1、201,301 或 401(每个公司范围显示)。

我也知道我必须创建一个循环来自动为我收集这些数据,而不是在保存每个表后手动替换 URL。通过阅读其他帖子和观看视频,我尝试了一些 sapply 功能的变体,但没有一个对我有用,我迷路了。

【问题讨论】:

标签: r web-scraping html-table


【解决方案1】:

一些帮助您入门的建议。首先,编写一个函数来下载和解析每个页面可能很有用,例如

getData <- function(year, start) {
  url <- sprintf("http://archive.fortune.com/magazines/fortune/fortune500_archive/full/%d/%d.html", 
    year, start)
  fileurl <- read_html(url)
  content <- fileurl %>%
    html_nodes(xpath = '//*[@id="MagListDataTable"]/table[2]') %>%
    html_table()
  contentframe <- data.frame(content)
}

然后,我们可以使用lapply(以及do.call(rbind, ...) 将每年的所有5 个数据帧rbind 一起)遍历年份和页面。例如:

D <- lapply(2000:2005, function(year) {
  do.call(rbind, lapply(seq(1, 500, 100), function(start) {
    cat(paste("Retrieving", year, ":", start, "\n"))
    getData(year, start)
    }))
})

【讨论】:

    猜你喜欢
    • 2021-04-06
    • 2015-01-15
    • 2020-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-08
    • 1970-01-01
    相关资源
    最近更新 更多