作為 R 網路抓取的新手,我希望對網路抓取專案問題有所幫助。我想抓取在此頁面上生成圖表的資料。
價格圖表
我檢查了 Chrome 中的頁面并確定了回傳資料的鏈接。
網站檢查截圖
使用此 URL,我創建了以下代碼來決議資料
url <- 'https://www.solactive.com/Indices/?indexhistory=DE000SL0BBT0&indexhistorytype=max'
index_data <- read_xml(url)
不幸的是,我收到了錯誤訊息
Error in read_xml.raw(raw, encoding = encoding, base_url = base_url, as_html = as_html, :
Failed to parse text
我檢查了具有以下內容的網頁
回應標頭
content-encoding: gzip
content-length: 20624
content-type: text/html; charset=UTF-8
date: Thu, 21 Apr 2022 00:33:05 GMT
server: nginx
strict-transport-security: max-age=63072000
vary: Accept-Encoding
接受標頭(快照)
accept: application/json, text/javascript, */*; q=0.01
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
我也嘗試應用以下編碼但沒有成功
index_data <- read_xml(url, encoding = "gzip, deflate, br")
我所追求的是一個帶有 index_id、日期、值的資料表
任何援助將不勝感激。
謝謝
uj5u.com熱心網友回復:
不知道為什么在 R 中,盡管設定了各種標頭,但回應仍然是 html,而在 Python 中,僅傳遞引薦來源標頭并回傳 JSON 就足夠了。但是,有點麻煩,您可以從p回應中的標簽中提取并使用 jsonlite 決議
library(httr2)
library(rvest)
headers = c('referer' = 'https://www.solactive.com/Indices/?index=DE000SL0BBT0')
params = list('indexhistory' = 'DE000SL0BBT0', 'indexhistorytype' = 'max')
data <- request("https://www.solactive.com/Indices/") |>
(\(x) req_headers(x, !!!headers))() |>
req_url_query(!!!params) |>
req_perform() |>
resp_body_html() |>
html_element('p') |>
html_text() |>
jsonlite::parse_json(simplifyVector = T)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/460006.html
上一篇:拆分列資料以創建新行
下一篇:在矩陣行中搜索并從R中的列回傳值
