首页 > 解决方案 > 使用 R 模拟单击​​“下载数据集”并将文件保存在不同的文件夹中

问题描述

我希望有人能够帮助我弄清楚如何抓取没有链接的 .csv 文件。

单击 R 中的下载按钮

我想让 R 下载单击本网站https://www.opentable.com/state-of-industry上第一个表旁边的“下载数据集”时生成的 .csv 文件。我发现与我的问题最接近的帖子是this,但我找不到解决方案中使用的 API 链接。

潜在的第二个问题:将下载的文件保存到另一个位置

理想情况下,我希望将文件加载到 R 中(类似于上面链接中的解决方案),但如果唯一的方法是在我的设备上下载它然后在 R 中读取它,那么我想要 . csv 文件安装在特定文件夹(例如 C:\Documents\OpenTable)并覆盖现有的同名文件。

谢谢!

标签: rpostweb-scrapinghttr

解决方案


那是因为这个页面没有调用任何API,CSV文件中的所有数据都在页面的JS代码中。您会在<script>包含covidDataCenter. 要将 JS 中创建的数据转换为 R 中的数据,您需要V8package.json 文件。然后,对数据进行一些转换:

library(rvest)
library(V8)
library(dplyr)
library(tidyr)
pg <- read_html("https://www.opentable.com/state-of-industry")
js <- pg %>% html_node(xpath = "//script[contains(., 'covidDataCenter')]") %>% html_text()
ct <- V8::new_context()
ct$eval("var window = {}") # the JS code creates a `window` object that we need to initialize first
ct$eval(js)
data <- ct$get("window")$`__INITIAL_STATE__`$covidDataCenter$fullbook # this is where the data sets get values
dates <- data$headers
countries <- data$countries 
states <- data$states
cities <- data$cities
# ALthough it's not straight-forward but you can achieve the datasets you want by this:
countries_df <- countries %>%
  unnest(yoy) %>%
  group_by(name, id, size) %>%
  mutate(
    date = dates
  ) %>%
  ungroup() %>%
  spread(date, yoy) %>%
  .[c("name", "id", "size", dates)] # arrange the columns
# similar to states and cities

将数据框导出为 CSV 文件write.csv()


推荐阅读