Re: [問題] 使用rvest無法爬出網頁的數值
※ 引述《j2225653 (水中魚)》之銘言:
: [問題類型]:
: 程式諮詢(我想用R 做某件事情,但是我不知道要怎麼用R 寫出來)
: [軟體熟悉度]:
: 新手(沒寫過程式,R 是我的第一次)
: [問題敘述]:
: 如圖
: https://i.imgur.com/ifORXBa.jpg

: 已知方法將綠框的數字爬下來
: 一樣方法想把網頁中的紅框中三個數值用rvest爬蟲下來卻無法
: [程式範例]:
: library(rvest)
: url <-"https://www.wantgoo.com/stock/1101?searchType=stocks"
: htmldata <- read_html(url)
: DATA1 <- htmldata %>% html_nodes(".idx-change span") %>% html_text()
: print(DATA1)
: #DATA1 可爬到我想要的數值
: DATA2 <- htmldata %>% html_nodes(".labs span") %>% html_text()
: print(DATA2)
: #DATA2卻一直爬到空值
: [環境敘述]:
: R version 3.4.4 (2018-03-15) -- "Someone to Lean On"
: Copyright (C) 2018 The R Foundation for Statistical Computing
: Platform: x86_64-w64-mingw32/x64 (64-bit)
: [關鍵字]:
: 爬蟲
認真爬一下javascript code的話就能看到他把那三個值寫在javascript的code裡面
程式:
library(rvest)
url <-"https://www.wantgoo.com/stock/1101?searchType=stocks"
htmldata <- read_html(url)
DATA2 <- htmldata %>% html_nodes("script") %>% sapply(html_text) %>%
`[`(grepl("^var execPrice", .)) %>% strsplit(";?\\s*var\\s+") %>% `[[`(1) %>%
`[`(2:4) %>% paste0(collapse = ",") %>% sprintf(fmt = "list(%s)") %>%
{eval(parse(text = .))}
print(DATA2)
# $execPrice
# [1] 44.8
#
# $supportPriceAvg
# [1] 40.75
#
# $preasurePriceAvg
# [1] 45.74
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 36.233.83.41
※ 文章網址: https://www.ptt.cc/bbs/R_Language/M.1528295928.A.76D.html
推
06/07 00:05,
7年前
, 1F
06/07 00:05, 1F
→
06/07 00:07,
7年前
, 2F
06/07 00:07, 2F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):
R_Language 近期熱門文章
PTT數位生活區 即時熱門文章