使用 Rvest 在 HTML 页面中获取 JS 嵌套元素

Fetch JS nested element in HTML page with Rvest

我正在尝试使用 Rvest 检索 this page 上的元素以将它们放入数据框中。

有一些文本似乎嵌套在我想要在我的 df 中的 JS 元素中,尽管我很难抓取它。

这是元素所在页面的代码:

<div class="js-unregulated-speciality-alert" data-props="{}">
  <div class="dl-alert dl-alert-unregulated-speciality dl-margin-t dl-alert-info dl-alert-size-medium">
    <div class="dl-alert-content">
        <svg class="dl-icon dl-margin-r-s dl-icon-small" width="16" height="16" fill="currentColor" viewBox="0 0 16 16">
            <path fill-rule="evenodd" clip-rule="evenodd" d="M8 14.4A6.4 6.4 0 108 1.6a6.4 6.4 0 000 12.8zm0-7.793a1.084 1.084 0 110-2.168 1.084 1.084 0 010 2.168zm1.135 4.696h-2.27a.31.31 0 01-.31-.31v-.619a.31.31 0 01.31-.31h.31v-1.65h-.31a.31.31 0 01-.31-.31v-.619a.31.31 0 01.31-.31h1.651a.31.31 0 01.31.31v2.58h.31a.31.31 0 01.31.31v.62a.31.31 0 01-.31.31z"></path></svg>
                <span class="dl-text dl-text-body dl-text-regular dl-text-s">
                    Ce praticien exerce une profession non réglementée.
            <span class="dl-underlined dl-cursor-pointer dl-font-700 dl-margin-l-xs">En savoir plus</span>
            </span>
    </div>
</div>

“Ce praticien exercise une professional non réglementée.” 这一点正是我需要抓取的。 此 R 代码仅 return 个空字符。

link <- "https://www.doctolib.fr/hypnotherapeute/paris/elsa-couteiller"        
page = read_html(link)
text = page %>%
   html_nodes("js-unregulated-speciality-alert") %>%
   html_text()

数据是从脚本标签动态加载的。您可以使用以下正则表达式提取个人资料信息,然后解析为 json 并提取您的目标短语:

library(rvest)
library(stringr)
library(dplyr)
library(jsonlite)

page <- read_html('https://www.doctolib.fr/hypnotherapeute/paris/elsa-couteiller') %>% toString()
res <- page %>% stringr::str_match("window.translation_keys = (.*\});\n") %>% .[2]
data <- jsonlite::parse_json(res)
print(data$root$profiles$show$unregulated_speciality)