【问题标题】:Web Scraping with rvest and xml2使用 rvest 和 xml2 进行网页抓取
【发布时间】:2020-04-15 02:29:48
【问题描述】:

我正在尝试从以下网址获取与 COVID 相关的公告的日期和政策类型:https://covid19.healthdata.org/united-states-of-america/alabama

我要确定的第一个日期是阿拉巴马州居家令的“2020 年 4 月 4 日”日期。

据我所知(因为我是新手),它有 xpath:

 "//[@id="root"]/div/main/div[3]/div[1]/div[2]/div[1]/div[1]/div/div/span"

我一直在使用以下几行来尝试检索它 -

data <- read_html(url) %>% 
  html_nodes("span.ant-statistic-content-value")

data <- read_html(url) %>%
  html_nodes(xpath = "//*[@id='root']/div/main/div[3]/div[1]/div[2]/div[1]/div[1]/div/div/span")

两者都无法提取我正在寻找的信息。任何帮助将不胜感激!

【问题讨论】:

  • 我认为rvest 不会在这个网站上工作。你可以试试selenium解决方案

标签: html r rvest


【解决方案1】:

此页面的数据存储在一系列 JSON 文件中。如果您使用浏览器中的开发人员工具并查找 XHR 类型的 Networks 文件;您应该获得与此类似的列表(下面的 Safari 浏览器):

右键单击名称以复制 URL 链接。

这个脚本应该让你开始:

library(jsonlite)
#obtain the list of locations
locations<-fromJSON("https://covid19.healthdata.org/api/metadata/location?v=7", flatten = TRUE)

head(locations[, 1:9])
#get list if US locations
US <- locations$children[locations$location_name =="United States of America"]
head(US[[1]])

#Get data frame from interventions
#Create link with desired location_id (569 is Virginia)
#paste0("https://covid19.healthdata.org/api/data/intervention?location=", "569")
Interventions <- fromJSON("https://covid19.healthdata.org/api/data/intervention?location=569", flatten = TRUE)

Interventions
# date_reported covid_intervention_id location_id covid_intervention_measure_id   covid_intervention_measure_name
# 1 2020-03-30 00:00:00                   110         569                             1 People instructed to stay at home
# 2 2020-03-16 00:00:00                   258         569                             2     Educational facilities closed
# 3 2020-04-19 00:00:00                   437         569                             7          Assumed_implemented_date

#Repeat for other links of interest

【讨论】:

  • 谢谢。是否有与 $children 解析器关联的包?对我来说,它返回 NULL(空)。
  • @Sophie,$children 是位置数据框的第 10 列。并非每个国家/地区都会在该列中嵌入数据框。请验证拼写和大小写是否正确。如果我复制并粘贴上面的脚本,它会按预期运行。
  • 已排序。我对 fromJSON() 的调用是推迟到 RJSONIO 包而不是 jsonlite 包。 jsonlite::fromJSON() 修复了它。非常感谢!
猜你喜欢
  • 2015-09-06
  • 1970-01-01
  • 2019-10-11
  • 1970-01-01
  • 2020-05-15
相关资源
最近更新 更多