看板 R_Language 關於我們 聯絡資訊
※ 引述《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
j2225653: 謝謝C大~我剛剛也有注意到了,只是不知道怎麼從裡面 06/07 00:05
j2225653: 擷取出來,我研究一下~太感謝了。 06/07 00:07