作者celestialgod (天)
看板R_Language
标题Re: [问题] 如何将html_nodes的资料转成CSV
时间Sun Dec 4 21:09:35 2016
※ 引述《lovedmagic (EricZou)》之铭言:
: [问题类型]:
: 程式谘询(我想用R 做某件事情,但是我不知道要怎麽用R 写出来)
: [软体熟悉度]:
: 新手(没写过程式,R 是我的第一次)
: [问题叙述]:
: 参考了一下板上的资讯,对於用rvest转CSV档还是不了解
: 请求指点迷津
: [程式范例]:
: if (!"installr" %in% installed.packages()) install.packages("installr")
: library(installr)
: require2(rvest)
: require2(stringr)
: require2(pipeR)
: ateam1 <- read_html("https://www.kickstarter.com/mexico?ref=hero")
: asd = html_nodes(ateam1, "ul.project-stats")
: html_text(asd)
: [1] "\n53% funded\n\n\nMX$ 24,235 pledged\n\n\nFunded\n\n\n\n\n\n
: [2] "\n4% funded\n\n\nMX$ 7,305 pledged\n\n\nFunded\n\n\n\n\n\n
: [3] "\n67% funded\n\n\nMX$ 54,050 pledged\n\n\nFunded\n\n\n\n\n\n
: 如果我将资料汇出成CSV有什麽办法呢?直接用write.csv会出现他是nodes
: 所以不能用data.frame的方式输出,而其实我只要53%- $24235 、4%
: - $7305 这两个资料,那我又有什麽其他的方法可以完成呢?
: [环境叙述]:
: Windows 7
: R 3.2.2
: [关键字]:
: html、网路爬虫
使用html_structure去看html的架构再根据架构去剖析出你要的资讯即可
示范如下:
if (!"installr" %in% installed.packages()) install.packages("installr")
library(installr)
require2(rvest)
require2(pipeR)
require2(plyr)
stats <- read_html("
https://www.kickstarter.com/mexico?ref=hero") %>>%
html_nodes("ul.project-stats")
# html_structure(stats[[1]]) # 用来查看node资料资讯
laply(stats, function(x){
c(
funded = html_node(x, "div.project-stats-value") %>>% html_text,
pledged = html_node(x, "span.money") %>>% html_text
)
})
可能剩下就是处理一些文字的,例如把%数跟$转成数字
--
R资料整理套件系列文:
magrittr #1LhSWhpH (R_Language) https://goo.gl/72l1m9
data.table #1LhW7Tvj (R_Language) https://goo.gl/PZa6Ue
dplyr(上.下) #1LhpJCfB,#1Lhw8b-s (R_Language) https://goo.gl/I5xX9b
tidyr #1Liqls1R (R_Language) https://goo.gl/i7yzAz
pipeR #1NXESRm5 (R_Language) https://goo.gl/zRUISx
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 36.232.188.79
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/R_Language/M.1480856978.A.EBB.html
1F:推 lovedmagic: 先服用看看 感谢 12/04 21:23