我正在尝试从几个姐妹 URL 中抓取数据进行分析。以前的线程抓取网页,页面上的链接,并使用 R 形成表格有助于使用以下脚本让我走上正确的道路:
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")
但是,应用到姐妹 URL 时,事情就坏了。试
#=======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)
)
例如,产生
## Error in data.frame(dates = xpathSApply(doc, "//*[@class=\"auto_archive\"]/li/a", :
arguments imply differing number of rows: 59, 60
http://www.who.int/csr/don/archive/year/2008/en/index.html和http://www.who.int/csr/don/archive/year/2006/也会出现类似的错误zh/index.html。我对 HTML 或 XML 不方便;任何想法表示赞赏。