我正试图从以下网址将最高法院大法官的表格加载到R中.
https://en.wikipedia.org/wiki/List_of_Justices_of_the_Supreme_Court_of_the_United_States
https://en.wikipedia.org/wiki/List_of_Justices_of_the_Supreme_Court_of_the_United_States
我正在使用以下代码:
scotusURL <- "https://en.wikipedia.org/wiki/List_of_Justices_of_the_Supreme_Court_of_the_United_States" scotusData <- getURL(scotusURL,ssl.verifypeer = FALSE) scotusDoc <- htmlParse(scotusData) scotusData <- scotusDoc['//table[@class="wikitable"]'] scotusTable <- readHTMLTable(scotusData[[1]],stringsAsFactors = FALSE)
R将scotusTable返回为NULL.这里的目标是在R中获得一个data.frame,我可以用来在法庭上制作SCOTUS正义任期的ggplot.我以前有脚本工作制作一个很棒的情节,但是在最近的决定之后,页面上的某些内容发生了变化,现在脚本将无法运行.我浏览了维基百科上的HTML以试图找到任何更改,但是我不是webdev所以任何破坏我的脚本的东西都不会立即显现出来.
另外,R中是否有一个方法可以让我从这个页面缓存数据,所以我不会经常引用URL?这似乎是未来避免这个问题的理想方式.
感谢帮助.
顺便说一句,SCOTUS在我正在进行的业余爱好/侧面项目中,所以如果有一些其他数据源比维基百科更好,我全都听见了.
编辑:对不起我应该列出我的依赖项.我正在使用XML,plyr,RCurl,data.table和ggplot2库.
解决方法
如果你不介意使用不同的包,你可以尝试“rvest”包.
library(rvest) scotusURL <- "https://en.wikipedia.org/wiki/List_of_Justices_of_the_Supreme_Court_of_the_United_States"
>选项1:从页面中获取表格并使用html_table函数提取您感兴趣的表格.
temp <- scotusURL %>% html %>% html_nodes("table") html_table(temp[1]) ## Just the "legend" table html_table(temp[2]) ## The table you're interested in
>选项2:检查表元素并复制XPath以直接读取该表(右键单击,检查元素,滚动到相关的“表”标记,右键单击它,然后选择“复制XPath”).
scotusURL %>% html %>% html_nodes(xpath = '//*[@id="mw-content-text"]/table[2]') %>% html_table
我喜欢的另一个选项是将数据加载到Google电子表格中并使用“googlesheets” package读取它.
在Google云端硬盘中,创建一个名为“Supreme Court”的新电子表格.在第一个工作表中,输入:
=importhtml("https://en.wikipedia.org/wiki/List_of_Justices_of_the_Supreme_Court_of_the_United_States","table",2)
这会自动将此表格划入您的Google电子表格中.
从那里,你可以做:
library(googlesheets) SC <- gs_title("Supreme Court") gs_read(SC)