1

我正在尝试从几个姐妹 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.htmlhttp://www.who.int/csr/don/archive/year/2006/也会出现类似的错误zh/index.html。我对 HTML 或 XML 不方便;任何想法表示赞赏。

4

2 回答 2

1

您可以先选择标题,然后找到与它们关联的 href

require(XML)
url2011 = 'http://www.who.int/csr/don/archive/year/2011/en/index.html'
doc <- htmlParse(url2011)
titleNodes <- getNodeSet(doc, '//*[@class="link_info"]')
hrefNodes <- sapply(titleNodes, getNodeSet, path = './preceding-sibling::a')

dummy2011 <- data.frame(
    dates = sapply(hrefNodes, xmlValue),
    hrefs = sapply(hrefNodes, xmlAttrs),
    title = sapply(titleNodes, xmlValue),
    stringsAsFactors = FALSE
)

更新:

删除可以使用的重复值

dummy2011 <- dummy2011[!duplicated(dummy2011$hrefs),]
于 2013-06-30T19:06:30.410 回答
0

在更仔细地查看了有问题的 HTML 代码后,我发现了一些不一致的地方,这些不一致会导致我正在应用的脚本出错。作为记录,以下工作(诚然丑陋和临时性 - 但它完成了工作):

#=======2011========================================================================
url2011 = 'http://www.who.int/csr/don/archive/year/2011/en/index.html'
doc <- htmlParse(url2011)

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)
title[5] <- "Influenza like illness in the United States of America Revised 7 December 2011"
title = title[-6]

dummy2011 <- data.frame(
  dates,
  hrefs,
  title
)

感谢那些帮助我解决这个问题的人,非常感谢。

于 2013-06-30T19:39:11.483 回答