簡體   English   中英

使用 Rvest 在 HTML 頁面中獲取 JS 嵌套元素

[英]Fetch JS nested element in HTML page with Rvest

我正在嘗試使用 Rvest 檢索 此頁面上的元素,以將它們放入 dataframe 中。

有一些文本似乎嵌套在我想要在我的 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 exerce une professional non réglementée”。 正是我需要刮的。 這個 R 代碼只返回一個空字符。

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM