rvest是由Hadley Wickham进行的网络抓取和解析程序包,灵感来自Python的Beautiful Soup。它利用Hadleyxml2包的libxml2绑定进行HTML解析。
作为tidyverse的一部分,通过rvest管道传递。它用
xml2::read_html 抓取网页的HTML,
然后可以使用CSS或XPath选择器将其html_node和html_nodes功能作为子集,并且
解析至R对象与像功能html_text和html_table。
要从R的Wikipedia页面上刮取里程碑表,代码应类似于
library(rvest) url <- 'https://en.wikipedia.org/wiki/R_(programming_language)' # scrape HTML from website url %>% read_html() %>% # select HTML tag with class="wikitable" html_node(css = '.wikitable') %>% # parse table into data.frame html_table() %>% # trim for printing dplyr::mutate(Description = substr(Description, 1, 70)) ## Release Date Description ## 1 0.16 This is the last alpha version developed primarily by Ihaka ## 2 0.49 1997-04-23 This is the oldest source release which is currently availab ## 3 0.60 1997-12-05 R becomes an official part of the GNU Project. The code is h ## 4 0.65.1 1999-10-07 First versions ofupdate.packagesandinstall.packagesfunct ## 5 1.0 2000-02-29 Considered by its developers stable enough for production us ## 6 1.4 2001-12-19 S4 methods are introduced and the first version for Mac OS X ## 7 2.0 2004-10-04 Introduced lazy loading, which enables fast loading of data ## 8 2.1 2005-04-18 Support for UTF-8 encoding, and the beginnings of internatio ## 9 2.11 2010-04-22 Support for Windows 64 bit systems. ## 10 2.13 2011-04-14 Adding a new compiler function that allows speeding up funct ## 11 2.14 2011-10-31 Added mandatory namespaces for packages. Added a new paralle ## 12 2.15 2012-03-30 New load balancing functions. Improved serialization speed f ## 13 3.0 2013-04-03 Support for numeric index values 231 and larger on 64 bit sy
虽然这会返回一个data.frame,但请注意,就像抓取数据的典型操作一样,还需要进行进一步的数据清理:在这里,格式化日期,插入NAs等。
请注意,不太一致的矩形格式的数据可能需要循环或其他进一步处理才能成功解析。如果网站使用jQuery或其他方式插入内容,read_html可能不足以进行抓取,因此RSelenium可能需要更强大的抓取工具。