我正在尝试使用SelectorGadget和rvest从 https://3g.dxy.cn/newh5/view/pneumonia 中抓取数据
我使用以下代码成功抓取了页面中的一些文本。
library(rvest)
url <- 'https://3g.dxy.cn/newh5/view/pneumonia'
webpage <- read_html(url)
TEXT_html <- html_nodes(webpage,'.descText___Ui3tV')
TEXT <- html_text(TEXT_html)
但是当我尝试使用以下代码选择最重要的数据(表中受感染的人数(的表
时TABLE_html <- html_nodes(webpage,'.areaBlock1___3V3UU p')
TABLE <- html_text(TABLE_html)
输出"character 0"
我想这是因为表中的数据看不到,因为它们是通过 API 刷新的,但我真的不知道如何解决这个问题
有人有想法吗?非常感谢
在此页面上,不会从 API 单独检索数据。它实际上存在于您下载的 html 页面中,但它在脚本标签中以 JSON 格式存在,rvest 无法读取它的原因是数据仅在页面加载后由 Javascript 添加到 DOM 中。要获取数据,您需要提取并解析 JSON:
library(rvest)
library(tibble)
library(jsonlite)
data <- 'https://3g.dxy.cn/newh5/view/pneumonia' %>%
read_html() %>%
html_node('#getAreaStat') %>% # This is the tag containing the JSON
html_text() %>% # Get the javascript from the node
strsplit("(getAreaStat = )|(}catch)") %>% # Carve out the JSON
unlist() %>%
`[`(2) %>% # Unlist and extract the JSON
fromJSON() # Parse the JSON
现在data
是一个数据框,其中包含来自 JSON 的所有信息。但是,data
的最后一列实际上是城市级数据框的列表。由于它们都具有相同的列名,因此它们可以与rbind
绑定在一起。然后,可以从data
中移除最后一列,以便您获得一个包含省级数据的数据框和另一个包含城市级数据的数据框。
city_data <- as_tibble(do.call(rbind, data$cities))
province_data <- as_tibble(data[, -8])
所以province_data
看起来有点像这样(中文符号没有复制过来,而是出现在 R 控制台中(
province_data
#> # A tibble: 33 x 7
#> provinceName provinceShortNa~ confirmedCount suspectedCount curedCount deadCount
#> <chr> <chr> <int> <int> <int> <int>
#> 1 ??? ?? 2714 0 52 100
#> 2 ??? ?? 207 0 4 0
#> 3 ??? ?? 173 0 3 0
#> 4 ??? ?? 168 0 0 1
#> 5 ??? ?? 143 0 0 0
#> 6 ??? ?? 132 0 0 0
#> 7 ??? ?? 106 0 0 0
#> 8 ??? ?? 95 0 0 0
#> 9 ??? ?? 91 0 2 1
#> 10 ??? ?? 90 0 0 0
#> # ... with 23 more rows, and 1 more variable: comment <chr>
city_data看起来像这样(再次,在控制台中正确打印了城市名称(。
#> # A tibble: 329 x 5
#> cityName confirmedCount suspectedCount curedCount deadCount
#> <chr> <int> <int> <int> <int>
#> 1 ?? 1590 0 47 85
#> 2 ?? 213 0 2 4
#> 3 ?? 173 0 0 1
#> 4 ?? 114 0 0 3
#> 5 ?? 91 0 0 0
#> 6 ?? 71 0 1 2
#> 7 ?? 70 0 0 0
#> 8 ?? 70 0 0 0
#> 9 ?? 65 0 0 0
#> 10 ?? 57 0 0 0
#> # ... with 319 more rows