作者celestialgod (天)
看板R_Language
标题Re: [问题] 使用rvest无法爬出网页的数值
时间Wed Jun 6 22:38:45 2018
※ 引述《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://webptt.com/cn.aspx?n=bbs/R_Language/M.1528295928.A.76D.html
1F:推 j2225653: 谢谢C大~我刚刚也有注意到了,只是不知道怎麽从里面 06/07 00:05
2F:→ j2225653: 撷取出来,我研究一下~太感谢了。 06/07 00:07