【问题标题】:Problems extracting data using JSON in R (getting a lexical error)在 R 中使用 JSON 提取数据时出现问题(出现词法错误)
【发布时间】:2022-07-05 07:04:02
【问题描述】:

与此处提出的问题相关:R - Using SelectorGadget to grab a dataset

library(rvest)
library(jsonlite)
library(magrittr)
library(stringr)
library(purrr)
library(dplyr)

get_state_index <- function(states, state) {
  return(match(T, map(states, ~ {
    .x$name == state
  })))
}

s <- read_html("https://www.opentable.com/state-of-industry") %>% html_text()
all_data <- jsonlite::parse_json(stringr::str_match(s, "__INITIAL_STATE__ = (.*?\\});w\\.")[, 2])
fullbook <- all_data$covidDataCenter$fullbook

hawaii_dataset <- tibble(
  date = fullbook$headers %>% unlist() %>%  as.Date(),
  yoy = fullbook$states[get_state_index(fullbook$states, "Hawaii")][[1]]$yoy %>% unlist()
)

我正在尝试从 State 选项卡中获取 Hawaii 数据集。该代码以前可以运行,但现在这部分代码会引发错误:

all_data <- jsonlite::parse_json(stringr::str_match(s, "__INITIAL_STATE__ = (.*?\\});w\\.")[, 2])

我收到错误:

Error: lexical error: invalid char in json text.                                        NA                      (right here) ------^

任何建议的解决方案?网站似乎在这一年保持不变,但什么类型的更改导致代码中断?

编辑:@QHarr 提出的解决方案:

all_data <- jsonlite::parse_json(stringr::str_match(s, "__INITIAL_STATE__ = ([\\s\\S]+\\});")[, 2])

这工作了一段时间,但似乎他们的网站再次更改了底层 HTML 代码。

【问题讨论】:

    标签: r web-scraping rvest


    【解决方案1】:

    如下所示更改正则表达式模式,以确保它正确捕获响应文本中所需的字符串,即用于 all_data 的 JavaScript 对象

    all_data <- jsonlite::parse_json(stringr::str_match(s, "__INITIAL_STATE__ = ([\\s\\S]+\\});")[, 2])
    

    注意:在 R 中,单个转义是双倍的,例如\\s 而不是上面显示的\s

    【讨论】:

    • 我怎么知道要改变什么正则表达式模式?他们似乎时不时地改变它。现在,您在解决方案中发布的正则表达式模式不再有效。
    • 是不是从这个来看:window.__INITIAL_STATE__={"authModal":{"isAuthModalOpen":f...} })(window)
    • 我周末去看看。请提醒我。
    • 谢谢。你有机会看看吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多