4

こんにちは、R を使用してインターネットからデータをスクレイピングするのは初めてで、悲しいことに、HTML と XML についてはほとんど知りません。次の親ページで各ストーリー リンクをスクレイピングしようとしています: http://www.who.int/csr/don/archive/year/2013/en/index.html。親ページの他のリンクは気にしませんが、各記事の URL の行と、対応する URL、記事のタイトル、日付の列を含むテーブルを作成する必要があります (常に記事の先頭にあります)。ストーリーのタイトルに続く最初の文)、次にページの残りのテキスト (テキストのいくつかの段落になる場合があります)。

「周期表」とすべてのリンク(およびいくつかの関連するスレッド)の Wiki ページをスクレイピングするのコードを適応させようとしましたが、問題が発生しました。アドバイスや指針をいただければ幸いです。これが私がこれまでに試したことです(「?????」で問題が発生しました):

rm(list=ls())
library(XML)
library(plyr) 

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

links = getNodeSet(doc, ?????)

df = ldply(doc, function(x) {
  text = xmlValue(x)
  if (text=='') text=NULL

  symbol = xmlGetAttr(x, '?????')
  link = xmlGetAttr(x, 'href')
  if (!is.null(text) & !is.null(symbol) & !is.null(link))
    data.frame(symbol, text, link)
} )

df = head(df, ?????)
4

1 に答える 1

7

Xpath を指定してドキュメントを検索することができますxpathSApply(ラップリーに相当)。

library(XML)
url = 'http://www.who.int/csr/don/archive/year/2013/en/index.html'
doc <- htmlParse(url)
data.frame(
  dates =  xpathSApply(doc, '//*[@class="auto_archive"]/li/a',xmlValue),
  hrefs = xpathSApply(doc, '//*[@class="auto_archive"]/li/a',xmlGetAttr,'href'),
  story = xpathSApply(doc, '//*[@class="link_info"]/text()',xmlValue))

 ##               dates                                                hrefs
## 1      26 June 2013             /entity/csr/don/2013_06_26/en/index.html
## 2      23 June 2013             /entity/csr/don/2013_06_23/en/index.html
## 3      22 June 2013             /entity/csr/don/2013_06_22/en/index.html
## 4      17 June 2013             /entity/csr/don/2013_06_17/en/index.html

##                                                                                    story
## 1                       Middle East respiratory syndrome coronavirus (MERS-CoV) - update
## 2                       Middle East respiratory syndrome coronavirus (MERS-CoV) - update
## 3                       Middle East respiratory syndrome coronavirus (MERS-CoV) - update
## 4                       Middle East respiratory syndrome coronavirus (MERS-CoV) - update

編集:各ストーリーのテキストを追加

dat$text = unlist(lapply(dat$hrefs,function(x)
  {
    url.story <- gsub('/entity','http://www.who.int',x)
    texts <- xpathSApply(htmlParse(url.story), 
                         '//*[@id="primary"]',xmlValue)
    }))
于 2013-06-30T00:15:21.680 に答える