r - 使用 R 模拟单击“下载数据集”并将文件保存在不同的文件夹中
问题描述
我希望有人能够帮助我弄清楚如何抓取没有链接的 .csv 文件。
单击 R 中的下载按钮
我想让 R 下载单击本网站https://www.opentable.com/state-of-industry上第一个表旁边的“下载数据集”时生成的 .csv 文件。我发现与我的问题最接近的帖子是this,但我找不到解决方案中使用的 API 链接。
潜在的第二个问题:将下载的文件保存到另一个位置
理想情况下,我希望将文件加载到 R 中(类似于上面链接中的解决方案),但如果唯一的方法是在我的设备上下载它然后在 R 中读取它,那么我想要 . csv 文件安装在特定文件夹(例如 C:\Documents\OpenTable)并覆盖现有的同名文件。
谢谢!
解决方案
那是因为这个页面没有调用任何API,CSV文件中的所有数据都在页面的JS代码中。您会在<script>
包含covidDataCenter
. 要将 JS 中创建的数据转换为 R 中的数据,您需要V8
package.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()
。
推荐阅读
- r - 如何在移动到R中for循环的下一行之前填充所有列?
- amazon-web-services - Gremlin 到 AWS Neptune 的 403 禁止错误
- java - 使用 ehcache 的倒排索引
- c# - 将编号项目反序列化为对象集合
- javascript - 如何使相同的 js 库在浏览器中工作并做出原生反应?
- android - admob 未定义 - Cordova CLI
- php - 成功插入数据后如何使用 API 向号码发送短信并将其重定向到我的网站页面
- python - 如何使用 scipy。整合。四正确?
- multithreading - 单个进程/线程会导致死锁吗?
- fiware - Fiware 查询中忽略大小写