我想從幾個姐姐網址上抓取數據進行分析。先前的線程Scraping a web page, links on a page, and forming a table with R是讓我在正確的道路上與下面的腳本有所幫助:在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)
)
例如,產生用於http://www.who.int/csr/don/archive/year/2008/en/index.html和http://www.who.int/csr/don/archive/year/2006/en/index.html發生
## Error in data.frame(dates = xpathSApply(doc, "//*[@class=\"auto_archive\"]/li/a", :
arguments imply differing number of rows: 59, 60
類似的錯誤。我對HTML或XML不太方便;任何想法讚賞。
我想這個錯誤是因爲你有多個故事的日期。腳本假定你有一對一的關係story-> date。 – agstudy
你可能會利用這些故事全部分組在'
'上來捕獲這些重複的「link_info」。 – Thomas謝謝,雖然我不清楚重複日期是否是問題 - 這個腳本適用於2012年(http://www.who.int/csr/don/archive/year/2011/en/index.html ),例如,併成功地刮擦了11月23日發生的三個故事。 – user2535366