Hadley Wickham’s post “rvest: easy web scraping with R” introduces the fine new package rvest
very well. For those now yearning a slightly more advanced example with a little help from pipeR + htmltools + XML
, I thought this might fill your yearn. The code grabs css information running the fancy new site cssstats.com on my blog site. With the background colors, it makes and labels some swatches and outputs them to the RStudio viewer--if installed--or your browser if not.
library(pipeR)
library(htmltools)
library(rvest)
library(XML)
# some slightly more advanced exercises
# using rvest, XML, and htmltools
# this one takes all the svg nodes in the section
# with id unique-background-colors from the
# site cssstats.com run on timelyportfolio.blogspot.com
# 1) removes attributes
# 2) sizes them at 85px x 64px
# 3) add new text node with fill value
# 4) combines them into a single div
# 5) with some meta information
"http://cssstats.com/stats?url=http%3A%2F%2Ftimelyportfolio.blogspot.com" %>>%
html %>>%
html_nodes( "#unique-background-colors svg" ) %>>%
xmlApply( function(x){
removeAttributes(x)
addAttributes(x,style="display:inline-block;height:85px;width:64px")
fillNode = newXMLNode(
"text"
,html_attr(html_node(x,"rect"),"fill")
,attrs=c(x=0,y=75,style="font-size:70%")
)
addChildren(x,fillNode)
saveXML(x) %>>% HTML
} ) %>>%
(tags$div(
style="display:inline-block;height:100%;width:100%"
,list(
tags$h3(
"Colors of TimelyPortfolio from "
,tags$a(href="http://cssstats.com","cssstats")
)
,.
)
)) %>>%
tagList %>>%
html_print
I just copied the div
output below in Windows Live Writer (notably from JJ Allaire and Joe Cheng of RStudio).
No comments:
Post a Comment