I am trying to scrape data from several sister URLs for analysis. A previous thread Scraping a web page, links on a page, and forming a table with R was helpful in getting me on the right path with the following script:
rm(list=ls())
library(XML)
library(RCurl)
#=======2013========================================================================
url2013 = 'http://www.who.int/csr/don/archive/year/2013/en/index.html'
doc <- htmlParse(url2013)
dummy2013 <- data.frame(
dates = xpathSApply(doc, '//*[@class="auto_archive"]/li/a', xmlValue),
hrefs = xpathSApply(doc, '//*[@class="auto_archive"]/li/a', xmlGetAttr,'href'),
title = xpathSApply(doc, '//*[@class="link_info"]/text()', xmlValue)
)
dummy2013$text = unlist(lapply(dummy2013$hrefs,function(x)
{
url.story <- gsub('/entity','http://www.who.int',x)
texts <- xpathSApply(htmlParse(url.story),
'//*[@id="primary"]',xmlValue)
}))
dummy2013$link <- gsub('/entity','http://www.who.int',dummy2013$hrefs)
write.csv(dummy2013, "whoDON2013.csv")
However, applied to sister URLs, things break. Trying
#=======2011========================================================================
url2011 = 'http://www.who.int/csr/don/archive/year/2011/en/index.html'
doc <- htmlParse(url2011)
dummy2011 <- data.frame(
dates = xpathSApply(doc, '//*[@class="auto_archive"]/li/a', xmlValue),
hrefs = xpathSApply(doc, '//*[@class="auto_archive"]/li/a', xmlGetAttr,'href'),
title = xpathSApply(doc, '//*[@class="link_info"]/text()', xmlValue)
)
for example, produces
## Error in data.frame(dates = xpathSApply(doc, "//*[@class=\"auto_archive\"]/li/a", :
arguments imply differing number of rows: 59, 60
Similar errors occur for http://www.who.int/csr/don/archive/year/2008/en/index.html and http://www.who.int/csr/don/archive/year/2006/en/index.html. I'm not handy with HTML or XML; any ideas appreciated.